if condition in Linux Shell Script
By: Dorris
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
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
#!/bin/sh
#
#Script to print file
#
if cat $1
then
echo -e "\n\nFile $1, found and successfully echoed"
fi
Run above script as:
$ chmod 755 showfile
$./showfile foo
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.
Detailed explanation
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.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
smskannel SMS gateway run in background
Running jar files in background in ssh window
Can't locate ExtUtils/MakeMaker.pm in @INC ...
Could not open '': No such file or directory at lib/ExtUtils/MM_Unix.pm line 2697
make: Nothing to be done for `all'.
How to burn your CD / DVD ISO image using Nero Burning ROM (Ahead Software) on Windows
How to burn your CD / DVD ISO image using Media Creator (Adaptec/Roxio) on Windows
How to burn your CD / DVD ISO image using Nero Express (Ahead Software) on Windows
How to burn your CD / DVD ISO image using NISO Recorder V2 Power Toy on Windows
Compiling and Installing software from source in Linux