Book Image

Linux Shell Scripting Cookbook - Third Edition

By : Clif Flynt, Sarath Lakshman, Shantanu Tushar
Book Image

Linux Shell Scripting Cookbook - Third Edition

By: Clif Flynt, Sarath Lakshman, Shantanu Tushar

Overview of this book

The shell is the most powerful tool your computer provides. Despite having it at their fingertips, many users are unaware of how much the shell can accomplish. Using the shell, you can generate databases and web pages from sets of files, automate monotonous admin tasks such as system backups, monitor your system's health and activity, identify network bottlenecks and system resource hogs, and more. This book will show you how to do all this and much more. This book, now in its third edition, describes the exciting new features in the newest Linux distributions to help you accomplish more than you imagine. It shows how to use simple commands to automate complex tasks, automate web interactions, download videos, set up containers and cloud servers, and even get free SSL certificates. Starting with the basics of the shell, you will learn simple commands and how to apply them to real-world issues. From there, you'll learn text processing, web interactions, network and system monitoring, and system tuning. Software engineers will learn how to examine system applications, how to use modern software management tools such as git and fossil for their own work, and how to submit patches to open-source projects. Finally, you'll learn how to set up Linux Containers and Virtual machines and even run your own Cloud server with a free SSL Certificate from letsencrypt.org.
Table of Contents (14 chapters)

Comparisons and tests

Flow control in a program is handled by comparison and test statements. Bash comes with several options to perform tests. We can use if, if else, and logical operators to perform tests and comparison operators to compare data items. There is also a command called test, which performs tests.

How to do it...

Here are some methods used for comparisons and performing tests:

  • Use an if condition:
        if condition; 
        then 
            commands; 
        fi
  • Use else if and else:
        if condition;  
        then 
            commands; 
        else if condition; then 
            commands; 
        else 
            commands; 
        fi 

Nesting is possible with if and else. The if conditions can be lengthy; to make them shorter we can use logical operators:

[ condition ] && action; # action executes if the condition is true

[ condition ] || action; # action executes if the condition is false

&& is the logical AND operation and || is the logical OR operation. This is a very helpful trick while writing Bash scripts.
Performing mathematical comparisons: usually, conditions are enclosed in square brackets []. Note that there is a space between [ or ] and operands. It will show an error if no space is provided.

[$var -eq 0 ] or [ $var -eq 0]

Perform mathematical tests on variables and values, like this:

[ $var -eq 0 ]  # It returns true when $var equal to 0. 
[ $var -ne 0 ] # It returns true when $var is not equal to 0

Other important operators include the following:

  • -gt: Greater than
  • -lt: Less than
  • -ge: Greater than or equal to
  • -le: Less than or equal to

The -a operator is a logical AND and the -o operator is the logical OR. Multiple test conditions can be combined:

[ $var1 -ne 0 -a $var2 -gt 2 ]  # using and -a 
[ $var1 -ne 0 -o var2 -gt 2 ] # OR -o

Filesystem-related tests are as follows:

Test different filesystem-related attributes using different condition flags

  • [ -f $file_var ]: This returns true if the given variable holds a regular file path or filename
  • [ -x $var ]: This returns true if the given variable holds a file path or filename that is executable
  • [ -d $var ]: This returns true if the given variable holds a directory path or directory name
  • [ -e $var ]: This returns true if the given variable holds an existing file
  • [ -c $var ]: This returns true if the given variable holds the path of a character device file
  • [ -b $var ]: This returns true if the given variable holds the path of a block device file
  • [ -w $var ]: This returns true if the given variable holds the path of a file that is writable
  • [ -r $var ]: This returns true if the given variable holds the path of a file that is readable
  • [ -L $var ]: This returns true if the given variable holds the path of
    a symlink

Consider this example:

fpath="/etc/passwd" 
if [ -e $fpath ]; then 
    echo File exists;  
else 
    echo Does not exist;  
fi

String comparisons: When using string comparison, it is best to use double square brackets, since the use of single brackets can sometimes lead to errors

Note that the double square bracket is a Bash extension. If the script will be run using ash or dash (for better performance), you cannot use the double square.

Test if two strings are identical:

  • [[ $str1 = $str2 ]]: This returns true when str1 equals str2, that is, the text contents of str1 and str2 are the same
  • [[ $str1 == $str2 ]]: It is an alternative method for string
    equality check

Test if two strings are not identical:

  • [[ $str1 != $str2 ]]: This returns true when str1 and str2 mismatch
Find alphabetically larger string:
Strings are compared alphabetically by comparing the ASCII value of the characters. For example, "A" is 0x41 and "a" is 0x61. Thus "A" is less than "a", and "AAa" is less than "Aaa".
  • [[ $str1 > $str2 ]]: This returns true when str1 is alphabetically greater than str2
  • [[ $str1 < $str2 ]]: This returns true when str1 is alphabetically lesser than str2
A space is required after and before =; if it is not provided, it is not a comparison, but it becomes an assignment statement.

Test for an empty string:

  • [[ -z $str1 ]]: This returns true if str1 holds an empty string
  • [[ -n $str1 ]]: This returns true if str1 holds a nonempty string

It is easier to combine multiple conditions using logical operators such as && and ||, as in the following code:

if [[ -n $str1 ]] && [[ -z $str2 ]] ;
   then
       commands;
   fi

Consider this example:

str1="Not empty " 
str2="" 
if [[ -n $str1 ]] && [[ -z $str2 ]]; 
then 
    echo str1 is nonempty and str2 is empty string. 
fi

This will be the output:

str1 is nonempty and str2 is empty string.

The test command can be used for performing condition checks. This reduces the number of braces used and can make your code more readable. The same test conditions enclosed within [] can be used with the test command.

Note that test is an external program which must be forked, while [ is an internal function in Bash and thus more efficient. The test program is compatible with Bourne shell, ash, dash, and others.

Consider this example:

if  [ $var -eq 0 ]; then echo "True"; fi 
can be written as 
if  test $var -eq 0 ; then echo "True"; fi