Home arrow Shell Programming arrow How to Evaluate an Expresion in Shell Scripting Language
How to Evaluate an Expresion in Shell Scripting Language PDF
Saturday, 23 January 2010
Next example evaluates if a=100, and if is true, it will echo a:

If evaluation example
  1. #!/bin/sh
  2.  
  3. a=100
  4.  
  5. if [ "$a" -eq 100 ]
  6. then
  7.         echo "a="$a
  8. fi


Here are some evaluation operators (comparissons):
-eq --- is equal to
-ne --- is not equal to
-gt --- is greater then
-ge --- is greater then or equal to
-lt --- is less then
-le --- is less then or equal to
=  --- is equal to, valid for string comparisons.

File operations (verify if):
-f --- file exists and is not a directory
-d --- directory exists
-s --- file exists and is not empty
-x --- file is executable
-r --- file is readable
-w --- file is writable

The followig example print "File exists" message, if a file install.log exists in the same directory as the script:

example2.sh
  1. #!/bin/sh
  2.  
  3. echo "Now I will verify if file install.log exists:"
  4.  
  5. if [ -f "install.log" ]
  6. then
  7.     echo "File exists"
  8. fi

 

You can also use else:

example3.sh
  1. $CD=/home/user/tmp
  2. cd $CD
  3. LOCATION=`pwd`
  4. if [ "$LOCATION" = "$CD" ]
  5. then
  6.         echo "Deleting from: "$CD
  7.         rm -Rf *
  8. else
  9.         echo "Error. Path for deleting files not found, exiting!"
  10.         exit 1
  11. fi

 

Last Updated ( Saturday, 26 March 2011 )
 
< Prev   Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?