if condition which is used for decision making in shell script, If given condition is true then command1 is executed.
Syntax:
if condition
then
command1 if condition is true or if exit status
of condition is 0 (zero)
...
...
fi
2. test command or [ expr ]
Syntax:
Mathematical Operator in Shell Script | Meaning | Normal Arithmetical/ Mathematical Statements | But in Shell | |
For test statement with if command | For [ expr ] statement with if command | |||
-eq | is equal to | 5 == 6 | if [ 5 -eq 6 ] | |
-ne | is not equal to | 5 != 6 | if test 5 -ne 6 | if [ 5 -ne 6 ] |
-lt | is less than | 5 < 6 | if [ 5 -lt 6 ] | |
-le | is less than or equal to | 5 <= 6 | if test 5 -le 6 | |
-gt | is greater than | 5 > 6 | if test 5 -gt 6 | |
-ge | is greater than or equal to | 5 >= 6 | if test 5 -ge 6 |
For string Comparisons use
Operator | Meaning |
string1 = string2 | string1 is equal to string2 |
string1 != string2 | string1 is NOT equal to string2 |
string1 | string1 is NOT NULL or not defined |
-n string1 | string1 is NOT NULL and does exist |
-z string1 | string1 is NULL and does exist |
Shell also test for file and directory types
Test | Meaning |
-s file | Non empty file |
-f file | Is File exist or normal file and not a directory |
-d dir | Is Directory exist and not a file |
-w file | Is writeable file |
-r file | Is read-only file |
-x file | Is file is executable |
Logical Operators
Logical operators are used to combine two or more condition at a timeOperator | Meaning |
! expression | Logical NOT |
expression1 -a expression2 | Logical AND |
expression1 -o expression2 | Logical OR |
3. if...else...fi
If given condition is true then command1 is executed otherwise command2 is executed.
Syntax:
if condition
then
condition is zero (true - 0)
execute all commands up to else statement
else
if condition is not true then
execute all commands up to fi
fi
4. Multilevel if-then-else
Syntax:
if condition
then
condition is zero (true - 0)
execute all commands up to elif statement
elif condition1
then
condition1 is zero (true - 0)
execute all commands up to elif statement
elif condition2
then
condition2 is zero (true - 0)
execute all commands up to elif statement
else
None of the above condtion,condtion1,condtion2 are true (i.e.
all of the above nonzero or false)
execute all commands up to fi
fi
5.
Syntax:
for { variable name } in { list }
do
execute one for each item in the list until the list is
not finished (And repeat all statement between do and done)
done
6.
Syntax:
while [ condition ]
do
command1
command2
command3
..
....
done
7. The case Statement
Syntax:
case $variable-name in
pattern1) command
...
..
command ;;
pattern2) command
...
..
command ;;
patternN ) command
...
..
command ;;
*) command
...
..
command ;;
esac
没有评论:
发表评论