Quantcast
Channel: Linux by Examples » echo
Viewing all articles
Browse latest Browse all 6

if … then … fi

$
0
0

if iis a basic programming checking for condition and reacts based on the condition, bash uses if to check for

  1. File
  2. integer
  3. 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

Viewing all articles
Browse latest Browse all 6

Trending Articles