Header Ads

3.4 : Linux - Shell Scripting - Intermediate



String tests: 

String comparison, Numeric comparison, File operators and logical operators
Comparison operations are provided below
Operator Meaning
= Compare if two strings are equal
!= Compare if two strings are not equal
-n Evaluate if string length is greater than zero
-z Evaluate if string length is equal to zero

Numeric tests

Operator Meaning
-eq Compare if two numbers are equal
-ge Compare if one number is greater than are equal to num
-le Compare if one number is less than or equal to a num
-ne Compare if two numbers are not equal
-gt Compare if one number is greater than another number
-lt Compare if one number is less than another number

Logical operators

Operator Meaning
! Negate (NOT) a logical expression
-a Logically AND two logical expression
-o Logically OR two logical expressions

For loop

Sequential loop with expressions
Syntax:
for (( EXPR1;EXPR2;EXPR3))
do
Code part

done

First arithmetic expr EXPR1 is evaluated; EXPR2 evaluated repeatedly until it evaluates to 0; Each time EXPR2 is evaluated to a non-zero value, statements are executed & EXPR3 is evaluated
While loop
The structure is a looping structure. Used to execute a set of commands while a specified condition is true
The loop terminates as soon as the condition becomes false. If condition never becomes false, loop will never exit.
Any valid conditional expression will work in the while loop.
Syntax:
while [ condition ]
do
code area;
done

Case statement

The case statement compares the value of the variable ($var in this case) to one or more values
Once a match is found, the associated commands are executed and the case statement is terminated
Used to execute statements based on specific values
Often used in place of an if statement if there are a large number of conditions.
Each set of statements must be ended by a pair of semicolon
*) is used for not matched with list of values
Syntax:
case "$var" in
value1)
commands;
;;
value2)
commands;
;;
*)
commands;
;;
esac

Functions:

Writing functions can greatly simplify a program
Improves modularity, readability and maintainability
However speed will get slowed down
Arguments are accessed as $1, $2, $3....

Arrays

An array is a variable containing multiple values may be of same type or of different type
There is no maximum limit to the size of an array
Array index starts with zero
Syntax:

declare -a arrayname=(element1 element2 element3)

"Here declare –a is optional, arrays can be declared without that also"

Command line arguments

Shell script can accept command-line arguments & options just like other Linux commands.
Within your shell script, you can refer to these arguments as $1,$2,$3,.. & so on.
Then the command line arguments are executed like
Read all command line arguments and print them

No comments