Table of Contents for
Learning Linux Shell Scripting

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Learning Linux Shell Scripting by Ganesh Sanjiv Naik Published by Packt Publishing, 2015
  1. Cover
  2. Table of Contents
  3. Learning Linux Shell Scripting
  4. Learning Linux Shell Scripting
  5. Credits
  6. About the Author
  7. Acknowledgments
  8. About the Reviewers
  9. www.PacktPub.com
  10. Preface
  11. What you need for this book
  12. Who this book is for
  13. Conventions
  14. Reader feedback
  15. Customer support
  16. 1. Getting Started and Working with Shell Scripting
  17. Tasks done by shell
  18. Working in shell
  19. Learning basic Linux commands
  20. Our first script – Hello World
  21. Compiler and interpreter – difference in process
  22. When not to use scripts
  23. Various directories
  24. Working more effectively with shell – basic commands
  25. Working with permissions
  26. Summary
  27. 2. Drilling Deep into Process Management, Job Control, and Automation
  28. Monitoring processes using ps
  29. Process management
  30. Process monitoring tools – top, iostat, and vmstat
  31. Understanding "at"
  32. Understanding "crontab"
  33. Summary
  34. 3. Using Text Processing and Filters in Your Scripts
  35. IO redirection
  36. Pattern matching with the vi editor
  37. Pattern searching using grep
  38. Summary
  39. 4. Working with Commands
  40. Command substitution
  41. Command separators
  42. Logical operators
  43. Pipes
  44. Summary
  45. 5. Exploring Expressions and Variables
  46. Working with environment variables
  47. Working with read-only variables
  48. Working with command line arguments (special variables, set and shift, getopt)
  49. Understanding getopts
  50. Understanding default parameters
  51. Working with arrays
  52. Summary
  53. 6. Neat Tricks with Shell Scripting
  54. The here document and the << operator
  55. The here string and the <<< operator
  56. File handling
  57. Debugging
  58. Summary
  59. 7. Performing Arithmetic Operations in Shell Scripts
  60. Using the let command for arithmetic
  61. Using the expr command for arithmetic
  62. Binary, octal, and hex arithmetic operations
  63. A floating-point arithmetic
  64. Summary
  65. 8. Automating Decision Making in Scripts
  66. Understanding the test command
  67. Conditional constructs – if else
  68. Switching case
  69. Implementing simple menus with select
  70. Looping with the for command
  71. Exiting from the current loop iteration with the continue command
  72. Exiting from a loop with a break
  73. Working with the do while loop
  74. Using until
  75. Piping the output of a loop to a Linux command
  76. Running loops in the background
  77. The IFS and loops
  78. Summary
  79. 9. Working with Functions
  80. Passing arguments or parameters to functions
  81. Sharing the data by many functions
  82. Declaring local variables in functions
  83. Returning information from functions
  84. Running functions in the background
  85. Creating a library of functions
  86. Summary
  87. 10. Using Advanced Functionality in Scripts
  88. Using the trap command
  89. Ignoring signals
  90. Using traps in function
  91. Running scripts or processes even if the user logs out
  92. Creating dialog boxes with the dialog utility
  93. Summary
  94. 11. System Startup and Customizing a Linux System
  95. User initialization scripts
  96. Summary
  97. 12. Pattern Matching and Regular Expressions with sed and awk
  98. sed – noninteractive stream editor
  99. Using awk
  100. Summary
  101. Index

Understanding the test command

Let's now understand the test command.

Using the test command with single brackets

Let's learn the following example to check the content or value of expressions:

$ test $name = Ganesh
$ echo $?
0 if success and 1 if failure.

In the preceding example, we want to check if the content of the variable name is the same as Ganesh and ? To check this, we have used the test command. The test will store the result of the comparison in the ? variable.

We can use the following syntax for the preceding test command. In this case, we used [ ] instead of the test command. We've enclosed the expression to be evaluated in square brackets:

$ [[ $name = Ganesh ]]      # Brackets replace the test command
$ echo $?
0

During the evaluation of expressions by test, we can even use wildcard expressions:

$ [[ $name = [Gg]????? ]]
$ echo $?
0

Therefore, we can either use the test command or square brackets for checking or evaluating expressions. Since word splitting will be performed on variables, if we are using text with white spaces, then we will need to enclose the text inside double quotes such as " ".

Using the test command with double brackets

Let's consider the case where we want to check whether there is the name Ganesh and if his friend is John. In this case, we will have multiple expressions to be checked using the AND operator &&. In such a case, we can use following syntax:

$ [[ $name == Ganesh && $friend == "John" ]]

Another way to do this is as follows:

[ $name == Ganesh ] && [ $friend == "John" ]

We used double brackets in the preceding expressions.

Here, we want to evaluate multiple expressions on the same command line. We can use the preceding syntax with AND (&&) or OR (||) logical operators.

String comparison options for the test command

The following is a summary of various options for string comparison using test which is taken from the Bash reference manual available at http://www.gnu.org/software/bash/:

Test operator

Tests true if

-n string

True if the length of string is nonzero.

-z string

True if the length of string is zero.

string1 != string2

True if the strings are not equal.

string1 == string2

string1 = string2

True if the strings are equal.

string1 > string2

True if string1 sorts after string2 lexicographically.

string1 < string2

True if string1 sorts before string2 lexicographically.

Suppose we want to check if the length of a string is nonzero, then we can check it as follows:

test –n $string      or     [ –n $string ]
echo $?

If the result is 0, then we can conclude that the string length is nonzero. If the content of ? is nonzero, then the string is 0 in length.

Let's write Shell script test01.sh for learning various string operations:

#!/bin/bash

str1="Ganesh";
str2="Mumbai";
str3=

[ $str1 = $str2 ] # Will Check Two Strings Are Equal Or Not
echo $?

[ $str1 != $str2 ] # Will Check Two Strings Are Not Equal
echo $?

[ -n $str1 ] # Will confirm string length is greater than zero
echo $?

[ -z $str3 ] # Will Confirm length of String is Zero
echo $?

Let's test the following program:

$ chmod +x test01.sh
$ ./test01.sh

The following will be the output after executing the preceding commands:

1
0
0
0

Let's write an interactive Shell script test02.sh to get names from the user and then compare if both are the same:

#!/bin/bash
echo "Enter First name"
read name1
echo "Enter Second name"
read name2
[ $name1 = $name2 ] # Check equality of two names
echo $?
[ -n  $name2 ] # Check String Length is greater than Zero
echo $?

Let's test the following program:

$ chmod +x test02.sh
$ ./test02.sh

The following will be the output after executing the preceding commands:

Enter First name
LEVANA
Enter Second name
TECHNOLOGIES
1
0

Numerical comparison operators for the test command

The following is the summary of various options for numerical comparison using test:

Numerical comparison operators for the test command

Let's write the Shell script test03.sh for learning various the numerical test operators' usage:

#!/bin/bash

num1=10
num2=30

echo $(($num1 < $num2))  # compare for less than
[ $num1 -lt $num2 ]      # compare for less than
echo $?
[ $num1 -ne $num2 ]      # compare for not equal
echo $?
[ $num1 -eq $num2 ]      # compare for equal to
echo $?

Let's test the following program:

$ chmod +x test03.sh
$ ./test03.sh

The following will be the output after executing the preceding commands:

1
0
0
1

Let's write the script test04.sh for interactively asking the user for three numbers and then testing those numbers for various comparisons:

#!/bin/bash
echo "Please enter 1st First Number"
read num1
echo "Please enter 2nd Number"
read num2
echo "Please enter 3rd Number"
read num3
[[ $num1 > $num2 ]]  # compare for greater than
echo $?
[[ $num1 != $num2 ]] # compare for not equal to
echo $?
[[ $num2 == $num3 ]] # compare for equal to
echo $?
[[ $num1 && $num2 ]] # Logical And Operation
echo $?
[[ $num2 || $num3 ]] # Logical OR Operation
echo $?

Let's test the following program:

$ chmod +x test04.sh
$ ./test04.sh

The following will be the output after executing the preceding commands:

Please enter 1st First Number
10
Please enter 2nd Number
20
Please enter 3rd Number
30
1
0
1
0
0

Let's write the script test05.sh for using string and numerical test operations:

#!/bin/bash
Var1=20
Var2=30
Str1="Accenture"
FileName="TestStringOperator"

test $Var1 -lt $Var2  # Test for Less Than
echo $?
test $Var1 -gt $Var2  # Test For Greater Than
echo $?
test -n $Str1         # Test for String Having Length Greater Than 0
echo $?
test -f $FileName     # Test for File Attributes
echo $?

Let's test the following program:

$ chmod +x test05.sh
$ ./test05.sh

The following will be the output after executing the preceding commands:

0
1
0
1

We used the test operation for the file in this script. It will check if the file is present. You will learn more about it in next section.

Now, we will write the script test06.sh using the test command interactively asking the user for data and then performing numerical as well as string comparison operations:

#!/bin/bash
echo "Please enter 1st Number"
read num1
echo "Please enter 2nd Number"
read num2
echo
test $num1 -eq $num2    # Test for Equal
echo $?
test $num1 -ne $num2    # Test for Not Equal
echo $?
test $num1 -ge $num2    # Test for Greater Than Equal
echo $?

echo "Please enter 1st String"
read Str1
echo "Please enter 2nd String"
read Str2

test $Str1 = $Str2    # Test for Two Strings Are Equal
echo $?
test -z $Str1        # Test for The Length Of The String Is > 0
echo $?
test $Str2        # Test for The String Is Not NULL
echo $?

Let's test the following program:

$ chmod +x test06.sh
$ ./test06.sh

The following will be the output after executing the preceding commands:

Please enter 1st Number
10
Please enter 2nd Number
20
1
0
1
Please enter 1st String
LEVANA
Please enter 2nd String
TECHNOLOGIES
1
1
0

Depending on the value of $? in the preceding output, we can decide whether the operation returned true or false. We will use this in if, case, and similar decision making, as well as in looping, activities.

File test options for the test command

The following are the various options for file handling operations using the test command:

File test options for the test command

File testing binary operators

The following are various options for binary file operations using test which is taken from the Bash reference manual available at http://www.gnu.org/software/bash/:

File testing binary operators

Let's write the script test07.sh to test the basic file attributes such as whether it is a file or folder and whether it has a file size bigger than 0. The output will be different if the case file is present or not:

#!/bin/bash
# Check if file is Directory
[ -d work ]
echo $?
# Check that is it a File
[ -f test.txt ]
echo $?
# Check if File has size greater than 0
[ -s test.txt ]
echo $?

Let us test the program:

$ chmod +x test07.sh
$ ./test07.sh

The following will be the output after executing the preceding commands:

1
1
1
$ mkdir work
$ touch test.txt
$ ./test07.sh
0
0
1

We executed the script with and without the directory and text.txt file.

The following script test08.sh is checking the file permissions such as read, write, and execute permissions:

#!/bin/bash
# Check if File has Read Permission
[ -r File2 ]
echo $?
# Check if File Has Write Permission
[ -w File2 ]
echo $?
# Check if File Has Execute Permission
[ -x File2 ]
echo $?

Let's test the program:

$ touch File2
$ ls -l File2
-rw-rw-r-- 1 student student    0 Jun 23 22:37 File2
$ chmod +x test08.sh
$ ./test08.sh

The following will be the output after executing the preceding commands:

0
0
1

Logical test operators

The following are the various options for logical operations using test which is taken from the Bash reference manual available at http://www.gnu.org/software/bash/:

Logical test operators

We can use the test operator for strings along with pattern matching as follows:

$ name=Ganesh
$ [[ $name == [Gg]anesh ]]      # Wildcards allowed
$ echo $?
0

The following is the example for multiple strings with the && logical operator:

$ name=Ganesh; friend=Anil
$ [[ $name == [Gg]anesh && $friend == "Lydia" ]]
$ echo $?
1

The following is the script with the test command along with the extended pattern matching enabled:

$ shopt -s extglob     # we are enabling extended pattern matching
$ city=Kannur
$ [[ $city == [Kk]a+(n)ur ]]
$ echo $?
0

In the given expressions, we are checking equality for strings. It tests if the city name starts with K or k, followed by a, one or more n characters, a u, and r.