By: Dorris Viewed: 613 times Printer Friendly Format
if condition which is used for decision making in shell script, If given
condition is true then command1 is executed.
if condition then command1 if condition is true or if exit status of condition is 0 (zero) ... ... fi
Condition is defined as:
"Condition is nothing but comparison between two values."
For compression you can use test or [ expr ] statements or even exist status can be also used.
Expreession is defined as:
"An expression is nothing but combination of values, relational operator (such as >,<, <> etc) and mathematical operators (such as +, -, / etc )."
Following are all examples of expression:
5 > 2
3 + 6
3 * 65
a < b
c > 5
c > 5 + 30 -1
Type following commands (assumes you have file called foo)
$ cat foo
$ echo $?
The cat command return zero(0) i.e. exit status, on successful, this can be used, in if condition as follows, Write shell script as
$ cat > showfile
#Script to print file
if cat $1
echo -e "\n\nFile $1, found and successfully echoed"
Run above script as:
$ chmod 755 showfile
Shell script name is showfile ($0) and foo is argument (which is $1).Then shell compare it as follows:
if cat $1 which is expanded to if cat foo.
if cat command finds foo file and if its successfully shown on screen, it means our cat command is successful and its exist status is 0 (indicates success), So our if condition is also true and hence statement echo -e "\n\nFile $1, found and successfully echoed" is proceed by shell. Now if cat command is not successful then it returns non-zero value (indicates some sort of failure) and this statement echo -e "\n\nFile $1, found and successfully echoed" is skipped by our shell.
Most Viewed Articles (in Linux )
Latest Articles (in Linux)
Comment on this tutorial
- Cloud Computing
- Java Beans
- Mac OS X
- Office 365
- Tech Reviews