if … then … fi

October 13th, 2006 mysurface Posted in Bash, echo, if, Misc | Hits: 83491 | 7 Comments »

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

7 Responses to “if … then … fi”

  1. Thanks alot I was looking for this information.

    End Thanks alot to open source comunity .

  2. Thank you. I’m also looking for this information

  3. 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

  4. 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.

  5. howdy! , I like your publishing extremely a lot! proportion many of us talk excess relating to your post for America online? I personally require an authority about this method to resolve our difficulty. Might be which is people! Looking onward to find out you.

  6. Good post however I was wondering if you could
    write a litte more on this subject? I’d be very grateful if you could elaborate a little bit more. Kudos!

  7. Hi, I do believe this is a great site. I stumbledupon it
    ;) I am going to revisit once again since i have book-marked it.
    Money and freedom is the greatest way to change, may you
    be rich and continue to help others.

Leave a Reply