Bash How to Compare Numbers

Bash How to Compare Numbers

The first option is to use the command test to binary compare numbers. For example:

if [ $a -eq $b ]; then
echo "a == b"
else
echo a!=b
fi

An operator”-eq” is equal to, -gt is greater than. For more operators type:

man test

If you are more familiar with symbols “<, >, <=, >=, ==” use double parentheses:

if (( $a < $b )); then
echo "a < b"
fi

For POSIX shells that don’t support double parentheses use test command.

Few examples of test options:

  • -ge: greater or equal
  • -le: less or equal
  • -lt: less than
  • -ne: not equal

Bash How to Return String from Function

Bash How to Return String from Function

You can return string from function in many ways, but you can not use the command “return” to return string:

return "Hello..."

Return statement can return only an integer value.

First option uses a passing argument to the function. To assign to the first argument use in function “$1”:

eval "$1='Hello...'"

Then call the function “my_function”:

my_var=''
my_function my_var
echo $my_var

Output: Hello…

Other way is to use a global variable which you modify within the function.

You can also use command echo to write string value and use command substitution to get it:

hello() {
var='Hello friend.'
echo "$var"
}

greeting=$(hello)
echo $greeting

Bash How to Check If File Exists

Bash How to Check If File Exists

What is the definition file in Linux? The file is almost everything – keyboard, and disk, and the regular file. Here is an example of a regular file: document.odt or /etc/passwd.

If you want the script to find out if there is any file (eg. tile.txt or /dev/sda), you can do the following:

if [ -e /root/file.txt ]; then
echo "File found";
fi

So, we tested if any kind of file (named /root/file.txt) exists.

If you want to take into consideration just regular files (not /dev/sda but just /root/file.txt), you can use -f parameter instead of -e parameter:

if [ -f /root/file.txt ]; then
echo "Regular file found";
fi

If you want to check, if a regular file not exists, you can use not(!) in test command []:

if [ ! -f /root/file.txt ]; then
echo "Regular file not found";
fi

We could tune the last example. You can also use short way how to write it:

[ ! -f /root/file.txt ] && echo "Regular file not found"

It is my favorite if you have just one command after the test command.

Here are some examples of file test operators:

Option Test
-s File is a regular file (if the file is directory or device returns false)
-d File is a directory
-b File is a block device
-c File is a character device
-p File is a pipe
-w File has a write permission

 

Bash Vs KSH

Bash Vs KSH

Linux and Unix have various shells. Two kinds of these numerous shells are KSH and BASH.

KSH (The Korn Shell) was developed many years before the BASH. Ksh has associative arrays and handles loop syntax better than bash. Also, ksh’s command print is better than bash’s echo command. In other way, ksh does not support history completion, process substitution, and rebindable command-line editing.

Bash has more added extension than ksh. Bash has tab completion and an easier method to set a prompt in order to display the current directory.

Compared to ksh, bash is newer and more popular.

Example of difference ksh and bash in condition test. First bash:

if [ $i -eq 3 ]

and condition test in ksh:

if (($i==3))

Bash can handle exit codes from pipes in a cleaner way. Bash and KSH are both Bourne=compatible shells, they share common functions and features and can be interchangeable to use.

Bash How to Quit a Script

Bash How to Quit a Script

The command “exit” terminate the script and return value:

Every command returns an exit status, sometimes it is called exit code or return status.

0: Script was executed with success.

1 and greater: Script was executed with error. The non-zero return value is interpreted as an “error code”.

If you want to get the exit value last executed script use $?.

./script.sh
echo $?

Sometimes you can see exit $? which is equivalent to exit.

Bash How to get Yesterday’s Date

Bash How to get Yesterday’s Date

Date command has d parameter, that displays time described after d parameter:

date -d yesterday '+%Y-%m-%d'

%Y means year, %m means month, and %d means day. You can change formatting if you want:

date -d yesterday '+%Y:%m:%d'

What if you want get several days, for example, day before 5 days?

date +%Y-%m-%d -d "5 day ago"

Would you take yesterday’s date to the variable?

YESTERDAY=`date -d yesterday '+%Y-%m-%d'`
echo $YESTERDAY

Alternative way is using hours:

date -d "24 hours ago" '+%Y-%m-%d'

Another way:

date --date='-1 day' '+%Y-%m-%d'

Bash How to Add Numbers

Bash How to Add Numbers

Bash provides a lot of methods how to add numbers. First of all is use $(())

echo $((2+2+1))

Output: 5

If we have a variable which has an integer value, we can use “$var”:

var=5
echo $((6+$var))

Output: 11

We can assign to variable counted numbers:

var=$((3+6))

The value of “var” is 9 now.

Another arithmetic expansion:
var=$((num1 + num2))
var=$(($num + $num2))
var=$((num1 + 10 + 20))
var=$[num1+num2]

Bash How to Format Date

Bash How to Format Date

The easiest way to get a date in YYYY-MM-DD is as follows:

date -I

Output: 2016-06-07

The parameter ā€œIā€ tells the date command, the ISO date format is required.

Of course, you can also use your own definition. %Y means year, %m means month, and %d means day:

date +%Y-%m-%d

Output: 2016-06-07, the same.

If you want to display also hours:minutes:second, let’s do:

date +%Y-%m-%d:%H:%M:%S

Output: 2016-06-07:17:02:19

You fill the variable date as follows:

DATE=`date +%Y-%m-%d:%H:%M:%S`

Here are some examples of format control:

  • %u – day of week(1..7), 1 is Monday
  • %w – day of week(0..6), 0 is Sunday
  • %U – week number of year, with Sunday as the first day of the week (00..53)
  • %V – week number of year, with Monday as the first day of the week (00..53)
  • %s – seconds since 1.1.1970 UTC
  • %Y – year
  • %y – last two digits of year(00..99)
  • %r – locale’s 12-hour clock time
  • %R – 24-hour hour and minute

Bash How to get Result of Command

Bash How to get Result of Command

To get the result of the command you need to use command substitution (bash feature). Command substitution provides executing a bash command/commands and store its output to a variable.

You can use special backticks (“). Everything what you write between backticks is executed by the shell before the main command is executed. Sometimes people call them back quotes. Surely you know that they’re under [Esc] key.

In this example, we get date into variables:

DATE=`date -I`
echo $DATE

If you expect multi-line output, and you would like to display it, it is good practice to use double quotes. In this example, we get all files in /etc into variable FILES:

FILES=$(ls /etc -l)
echo "$FILES"

What if you want to use backticks into backticks? It is a little trouble. The solution is to use a dollar with brackets $(). This example does the same:

DATE=$(date -I)
echo $DATE

It is also possible to use the inner way. In the next example, the output of date will be used as the first echo argument:

echo `date -I`

Bash How to Pass Array to Function

Bash How to Pass Array to Function

To pass all array items as arguments to the function using the following syntax:

my_function "${array[@]}"

To get values from the array in function use:

array_in_function=("$@")

If you would use “$1” instead of (“$@”) you get the first item from the array, “$2”-second item and etc.

Here is an example of the function “array_echo” which writes all items of the array.

function array_echo() {
arr=("$@")
for i in "${arr[@]}"; do
echo -n "$i "
done
}

array=(1 2 3 4 5 )
array_echo "${array[@]}"

Note: The “n” option in the echo command doesn’t output the trailing newline.

Actually, it is not passing an array as a variable, but as a list of its elements. In our example, you can not change values of array items from function array_echo().

Bash How to Measure Execution Time

Bash How to Measure Execution Time

The command “time” report an execution time information

time sleep 1

Output:
real 0m1.001s
user 0m0.000s
sys 0m0.001s

Description:

  • Real-time from start to finish
  • User – the amount of CPU time spent in use mode. It is the actual CPU time used in executing the process
  • Sys – the amount of CPU time spent in kernel

You can measure execution time by subtraction start date and end date:

start=`date +%s`
commands...
end=`date +%s`
echo Execution time was `expr $end - $start` seconds.

If you need to have more accurate measures:

start=`date +%s%N`
commands...
end=`date +%s%N`
echo Execution time was `expr $end - $start` nanoseconds.

Adding %N to date +%s causes nanosecond accuracy.