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 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 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.

Bash How to Sum Variables

Bash How to Sum Variables

Let’s define two variables:

FILES_ETC=1416
FILES_VAR=7928

If you want to get total value, you can do:

TOTAL_FILES=$((FILES_ETC+FILES_VAR))
echo $TOTAL_FILES

For 100% compatibility with old shells, you can use external command expr. In modern systems (ec. Centos 7 64bit), in fact, expr is not an external command. It is an internal shell function. So there is not a significant difference in speed between the above and this command:

TOTAL_FILES=`expr $FILES_ETC + $FILES_VAR`
echo $TOTAL_FILES

Funny thing is that there must be spaces between arguments. In fact, expr is a command, $FILES_ETC is the first argument, + is the second argument and $FILE_VAR is the third argument.

If you want to add numbers with decimal points, you can use bc. bc is a very useful external command for making arithmetical operations:

TOTAL_FILES=$(echo $FILES_ETC + $FILES_VAR | bc)
echo $TOTAL_FILES

Common mistakes are spaces before or after ‘=’ sign. However bc and expr commands expect spaces between arguments and operators, so in these cases don’t forget to spaces.

Bash How to Use Variables

Bash How to Use Variables

Firstly, you have to declare a variable:

var="Hello"

To get value from variable use the symbol “$” before variable name like in the following example:

echo $var friends.

Output: Hello friends.

Curly brackets “{}” are used to expand variables in the string. Often use to append string after variable value:

echo ${var}ween

Output: Helloween

If we didn’t use “{}” around var, the echo would only write an empty line.

There are examples of special variables:

  • $0 – Name of the bash script.
  • $# – How many arguments were passed to the script.
  • $? – Exit code of the last run process.
  • $$ – Process ID of the actual script.
  • $HOSTNAME – Hostname of the machine that script is running on.
  • $LINENO -Current line number in the script.