if … then … fi
October 13th, 2006 mysurface Posted in Bash, echo, if, Misc | Hits: 68716 | 4 Comments »
if iis a basic programming checking for condition and reacts based on the condition, bash uses if to check for
- File
- integer
- String
For checking the File, let say your file name is stored at $fn, and you wanna check the file is exist ? do this:
if [ -e $fn ]
then
echo "$fn exist."
else
echo "$fn does not exist."
fi
Bellow are the list of other common File checking,
| -e, -a | File exist |
| -f | File is a regular file |
| -d | File is a directory |
| -s | File is non-zero size |
| -h, -L | File is a symbolic link |
| -r, -w, -x | Check file permission |
| -u | File’s suid flag is set |
| -O | File owner is you |
| -G | File group same as yours |
| ! | “Notâ€, reverse |
To check for integer, let say we read user input and store at $num, and check whether is it greater than 10
read num;
if [ $num -gt "10" ]
then
echo "$num is greater than 10"
fi
Bellow are other common Integer checking.
| -eq | Is equal to |
| -ne | Not equal to |
| -gt | Greater than |
| -ge | Greater or equal |
| -lt | Less than |
| -le | Lesser or equal |
You can uses <, <=, >, >= but you need to put that into if ((…)), let say
if (($num >= "10" ))
then
echo "$num greater than 10"
fi
Now check for string, uses if [[...]] instead of if[...] will reduce a lots of problem of adding escape character. Let say now i wanna compare 2 string to see whether they are similar, $str1, $str2.
if [[ $str1 = $str2 ]]
then
echo "They are equal."
fi
Bellow are other common string checking
| =, == | Is equal to |
| != | Not equal to |
| > | Greater than |
| < | Less than |
| -z | Null string |
| -n | Not null string |







July 26th, 2010 at 6:30 pm
Thanks alot I was looking for this information.
End Thanks alot to open source comunity .
June 25th, 2011 at 11:43 pm
Thank you. I’m also looking for this information
October 28th, 2012 at 8:43 pm
I delight in, result in I found exactly what I used to be taking a look for. You have ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye
October 29th, 2012 at 1:55 am
certainly like your web site but you need to take a look at the spelling on quite a few of your posts. Many of them are rife with spelling issues and I find it very troublesome to tell the reality on the other hand I’ll surely come back again.