Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Linux Shell Scripting Cookbook, Second Edition

You're reading from   Linux Shell Scripting Cookbook, Second Edition Don't neglect the shell ‚Äì this book will empower you to use simple commands to perform complex tasks. Whether you're a casual or advanced Linux user, the cookbook approach makes it all so brilliantly accessible and, above all, useful.

Arrow left icon
Product type Paperback
Published in May 2013
Publisher Packt
ISBN-13 9781782162742
Length 384 pages
Edition 2nd Edition
Tools
Arrow right icon
Toc

Table of Contents (16) Chapters Close

Linux Shell Scripting Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
1. Shell Something Out FREE CHAPTER 2. Have a Good Command 3. File In, File Out 4. Texting and Driving 5. Tangled Web? Not At All! 6. The Backup Plan 7. The Old-boy Network 8. Put on the Monitor's Cap 9. Administration Calls Index

Comparisons and tests


Flow control in a program is handled by comparison and test statements. Bash also comes with several options to perform tests that are compatible with the Unix system-level features. We can use if, if else, and logical operators to perform tests and certain comparison operators to compare data items. There is also a command called test available to perform tests. Let us see how to use these.

How to do it...

We will have a look at all the different methods used for comparisons and performing tests:

  • Using an if condition:

    if condition;
    then
        commands;
    fi
  • Using else if and else:

    if condition; 
    then
        commands;
    else if condition; then
        commands;
    else
        commands;
    fi

    Note

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

    • [ 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. An example is as follows:

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

    Performing mathematical conditions over variables or values can be done as follows:

    [ $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 are as follows:

    • -gt: Greater than

    • -lt: Less than

    • -ge: Greater than or equal to

    • -le: Less than or equal to

    Multiple test conditions can be combined as follows:

    [ $var1 -ne 0 -a $var2 -gt 2 ]  # using and -a
    [ $var1 -ne 0 -o var2 -gt 2 ] # OR -o
  • Filesystem related tests: We can test different filesystem-related attributes using different condition flags as follows:

    • [ -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

    An example of the usage is as follows:

    fpath="/etc/passwd"
    if [ -e $fpath ]; then
        echo File exists; 
    else
        echo Does not exist; 
    fi
  • String comparisons: While using string comparison, it is best to use double square brackets, since the use of single brackets can sometimes lead to errors.

    Two strings can be compared to check whether they are the same in the following manner:

    • [[ $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

    We can check whether two strings are not the same as follows:

    • [[ $str1 != $str2 ]]: This returns true when str1 and str2 mismatch

    We can find out the alphabetically smaller or larger string as follows:

    • [[ $str1 > $str2 ]]: This returns true when str1 is alphabetically greater than str2

    • [[ $str1 < $str2 ]]: This returns true when str1 is alphabetically lesser than str2

      Note

      Note that a space is provided after and before =, if it is not provided, it is not a comparison, but it becomes an assignment statement.

    • [[ -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 || in the following code:

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

    For example:

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

    Output:

    str1 is nonempty and str2 is empty string.

The test command can be used for performing condition checks. It helps to avoid usage of many braces. The same set of test conditions enclosed within [] can be used for the test command.

For example:

if  [ $var -eq 0 ]; then echo "True"; fi
can be written as
if  test $var -eq 0 ; then echo "True"; fi
You have been reading a chapter from
Linux Shell Scripting Cookbook, Second Edition - Second Edition
Published in: May 2013
Publisher: Packt
ISBN-13: 9781782162742
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image