Bash How to Pass Arguments

Bash How to Pass Arguments

The special shell variable “$@” represents a list of all arguments that is passed to the script.

If you want to pass all arguments to your function, you can use this syntax:

function_name "$@"

If you want to pass all arguments to another script, you can use this syntax:

script_mame "$@"

Let’s take an example called passit.sh. In this script, we defined function print_argument, that print argument that comes from the command line:

#!/bin/bash

# function's definition
function PRINT_ARGUMENTS()
{
echo "Arguments of shell are: $@"
}

# in this place we want to call function
PRINT_ARGUMENTS "$@"

Let’s try to execute passit.sh in this way:

chmod u+x ./passit.sh
./passit.sh aa bb cc

Output: Arguments of the shell are: aa bb cc

You can see that function obtains all shell arguments, which were written in the bash command line.

To get a number of arguments use:

echo "Number of arguments of shell are: $#"

It is often used to check if a required number is equal to some value.

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 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 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 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 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 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 Assign Output to Variable

Bash How to Assign Output to Variable

Backquotes (“) are used for command substitution.

var=`date`

Command “date” return date to variable “var”. The alternative method to using command substitution is “$()”:

var =$(date)

If we want to get value from “var” use “$var”:

echo "$var"

Output: Tue Jul 12 15:33:06 CEST 2016

It properly always uses double quotes around variable substitution. Without double quotes, the variable is expanded which may cause problems if the variable contains special characters.

Make sure there is no space between variable name before and after assign char (=). You can assign output from pipeline to a variable:

NUM_FILES=`ls | wc -l`

Bash How to Stop Script

Bash How to Stop Script

If you want to stop the bash script, that is currently running, you can do the following sentence in bash:

kill $(ps aux | grep name_of_scirpt | grep -v grep | awk '{ print $2 }')

Command ps aux will give you all processes that are currently running. Grep will filter the name that you want to kill. You should be very specific, in another word, the whole name of the process name should be used here. Grep -v grep will filter grep process. AWK will filter the second column from the output, that is PID (process id).

If you want to stop script on a specific line, just add

exit 45

This line exits your script and gives 45 to the parent process. You can choose a number between 0 – 255. Number 0 is special, it means that your script exits without any problem. Any number between 1 – 255 means that something wrong happens in your script.

If you want to stop your script, if 1st error occurs, just add in hashpling line (1st line of the script) -e parameter:

#!/bin/bash -e
...
command1
command2
command3

This script will terminate immediately if some line fails. What means that line of the script fails? It means that line will exit with a non-zero exit code (1-255). For example, if command2 fails (return non-zero exit code), command3 will not be executed, at all.

I love this option in a test environment. It helps me to avoid unnecessary script execution after failure. I also like the bash -u parameter that exits your script if you use an uninitialized shell variable.

If you want to get the exit code of the last command enter:

echo $?

Bash will print integer values between 0 and 255.