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 Function How to Return Value

Bash Function How to Return Value

Bash functions have “return” statement, but it only indicates a return status (zero for success and a non-zero value for failure).

function myfunc() {
var='some text'
echo Hello..
return 10
}

myfunc
echo "Return value of previous function is $?"

Output: Hello.. Return value of the previous function is 10

If you want to return value you can use a global variable.

var=0
string () {
var="My return value."
}
string; echo $var

Output: My return value.

It is simple, but using global variables in complex scripts or programs causes harder methods to find and fix bugs.

We can use command substitution and assign an output from function:

string () {
local local_var="Value from function."
echo $local_var
}

var=$( string )
echo $var

Output: Value from function.

It’s good practice to use within-function local variables. Local variables are safer from being changed by another part of the script.

Bash How to Echo Array

Bash How to Echo Array

You can define three elements array (there is no space between the name of an array variable, equal symbol, and starting bracket):

FILES=(report.jpg status.txt scan.jpg)

This command will write each element in the array:

echo ${FILES[*]}

Index in shell arrays starts from 0. So, if you want to write just the first element, you can do this command:

echo ${FILES[0]}

Output: report.jpg

Do you want to process each element in the array in the loop? Here is an example:

for ELEMENT in ${FILES[@]}
do
echo File: $ELEMENT.
done

If you want to get only indexes of the array, try this example:

echo ${!FILES[@]}

“${!FILES[@]}” is a relatively new bash feature, it was not included in the original array implementation.

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 Get Exit Status

Bash How to Get Exit Status

The answer is in this special shell variable “$?”. In this variable is saved exit status of the last command that ended in the background.

In the next example “paranormal_directory” doesn’t exists, at all. It is a paranormal directory 🙂 In this example, $? variable will be 2, because command ls fails:

ls paranormal_directory 1>/dev/null 2>&1
echo $?

Output: 2

Listing the home folder is always safe. Executing ls without any parameter lists home folder of the current user. In this example, ls will succeed, so variable “$?” will be 0:

ls 1>/dev/null 2>&1
echo $?

Output: 0

But be careful, if you read this variable two times (echo $?). In the next example, “echo $?” (on line 3) will show you the output of the first echo command (on line 2):

ls paranormal_directory 1>/dev/null 2>&1
echo $?
echo $?

Output: 2 0

What happens if you don’t specify the exit code in the script? When the exit code is not specified with the exit command, the exit code of the script will be the exit code of the last executed command.

Bash How to Run Command from Variable

Bash How to Run Command from Variable

You can run the command from variable using the command “eval”:

eval $foo

The command eval takes an argument, construct and execute the command of it.

Another option is the symbol “$”:

$foo

Let’s have the following example:

foo='date'
foo2='echo "Hello :)"'
eval $foo
$foo2

Output: Wed Jul 27 14:17:40 CEST 2016 Hello 🙂

It is also possible to use bash’s option -c which executes commands from variables in a separate script, that inherits file descriptors, environment variables.

bash -c "$foo"

eval “$foo” executes the command in the current script, not in a separate script. If you want to execute the eval command in a separate script, use brackets: (eval “$1”).

Bash Color Shell Prompt

Bash Color Shell Prompt

You can customize 4 prompts: PS1 (Primary prompt, displayed before each command), PS2 (secondary prompt, displayed when a command needs more input), PS3 (rarely used, displayed for Bash’s select built-in which displays interactive menus).

Display current bash prompt (PS1) settings:

echo $PS1

Output: [\u@\h \W]\$

It is the default setting. The backslash-escaped characters means: \u (username), \h (hostname), \W (current working directory).

To modify colors to the prompt use following syntax:

\e[x;ym $PS1 \e[m

Meaning: \e[ (start color scheme), x;y (color pair to use), $PS1 (shell prompt variable), \e[m (stop color scheme)

To set red color enter:

export PS1="\e[0;36m[\u@\h \W]\$ \e[m "

Few examples of color codes:

  • black(0;30)
  • red (0;31)
  • greed (0;32)
  • brown (0;33)
  • blue (0;34)
  • purple (0:35)
  • cyan (0:36)

If you replace digit 0 with 1 you get a lighter color version.
Setting variable PS1 is temporary, when you log out your settings will be lost. You have to append the following line to $HOME/.bash_profile file or $HOME/.bashrc file:

export PS1="\e[0;36m[\u@\h \W]\$ \e[m "

Now ur new prompt color is permanent.

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 Yes to All

Bash Yes to All

Do you remember when Homer Simpson worked at home? Long did not enjoy it. Therefore he is represented by birds, which automatically screen by pressing the “y” key. How could this be done in BASH?

Yes command inserts the “y” character of STDIN infinitely times.

yes

You can use it in way of STDIN redirection to another command:

yes y | command

Let’s write a small script, that will expect three lines of text from you:

#!/bin/bash
read AAA
read BBB
read CCC
echo "$AAA, $BBB, $CCC"

Now, try to execute our script with yes in pipe:

yes | ./read.sh

If you want o give the opposite answer to our script, it is possible. Just pass string argument to yes:

yes n | ./read.sh

If script expects capital ‘Yes’ use:

yes Yes | ./read.sh

Some commands have an “assume-yes” flag ‘-y’, for example: yum, apt-get.

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'