Bash - If then else

About

if execute commands based on conditional expression.

Syntax

if COMMANDS; then 
COMMANDS; 
[ elif COMMANDS; then COMMANDS; ]... 
[ else COMMANDS; ] 
fi
  • The if COMMANDS list is executed.
  • If its exit status is:
    • zero, then the then COMMANDS list is executed.
    • Otherwise, each elif COMMANDS list is executed in turn, and if its exit status is zero:
      • the corresponding then COMMANDS list is executed and the if command completes.
      • Otherwise, the else COMMANDS list is executed, if present.

Nested if example

if [expression];
then
  expression
else
  if [expression];
  then 
     code if 'expression' is true.
  fi
fi 

Exit Status

The exit status of the entire construct is:

  • the exit status of the last command executed,
  • or zero if no condition tested true.

Operator

Date Comparison

Name Double Bracket operator Single Bracket Operator Example
RegularExpression matching =~ (not available) [[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!"

Integer Comparison

Boolean Expression (And/Or)

Name Double Bracket operator Single Bracket Operator Example
And && -a (**) [[ -n $var && -f $var ]] && echo "$var is a file"
Or || -o (**) [[ -b $var || -c $var ]] && echo "$var is a device"

Example:

if [ ${PATH_FILE:0:1} != "/" -a ${PATH_FILE:0:1} != "." ] 
then
   PATH_FILE="`pwd`/${PATH_FILE}";
fi

File

Name Double Bracket operator Single Bracket Operator Example
entry (file or directory) exists -e Na [[ -e $config ]] && echo "config file exists: $config"
file is newer/older than other file -nt / -ot Na [[ $file0 -nt $file1 ]] && echo "$file0 is newer than $file1"
two files are the same -ef Na [[ $input -ef $output ]] && { echo "will not overwrite input file: $input"; exit 1; } 
negation ! Na [[ ! -u $file ]] && echo "$file is not a setuid file"

Exit Status

Bash - (Return|Exit) (Value|Status)

commando

# The output
if [ $? != 0 ]; then
	echo "Commando goes bad"
	else
	echo "Commando goes good"
fi

Example

if [ "foo" = "foo" ]; then
   echo expression evaluated as true
else
    echo expression evaluated as false
fi

Documentation / Reference


Powered by ComboStrap