Bash - Conditional Expression

About

A Conditional Expression is a command that returns an exit status of 0 or 1 (This is known as a predicate or boolean expression).

This mostly used as command in a if statement

The conditional expression is part of the compound expression.

Syntax

[ conditional_expression ]
# or without word spliting and pathname expansion
[[ conditional_expression ]]
# or 

where:

  • [] defines a conditional expression evaluation
  • [[]] defines a conditional expression evaluation where Word splitting and pathname expansion are not performed
  • conditional_expression is a conditional expression
  • Return a status of 0 or 1

Note:

Test

To test a conditional expression, see the test command

test conditional_expression

Expression

Boolean Expression (And/Or)

Name Double Bracket operator Single Bracket Operator
And && -a (**)
Or || -o (**)

Example:

  • Double Bracket And
[[ -n $var && -f $var ]] && echo "$var is a file''
  • Double Bracket Or
[[ -b $var || -c $var ]] && echo "$var is a device"
  • Single Bracket And
if [ ${PATH_FILE:0:1} != "/" -a ${PATH_FILE:0:1} != "." ] 
then
   PATH_FILE="`pwd`/${PATH_FILE}";
fi

Date Comparison

Name Double Bracket operator Single Bracket Operator
RegularExpression matching =~ (not available)

Double Bracket example

[[ $(date) =~ ^Fri\ ...\ 13 ]] && echo "It's Friday the 13th!"

Comparison Operator

Comparison operator. They works on string and integer

Double Bracket operator Single Bracket Operator Example
-lt -lt [[ 8 -lt 9 ]] && echo "8 is less than 9"
-ge -ge [[ 3 -ge 3 ]] && echo "3 is greater than or equal to 3"
-gt -gt [[ 5 -gt 10 ]] || echo "5 is greater than than 10"
-le -le [[ 3 -le 8 ]] && echo "3 is less than or equal to 8"
-eq -eq [[ 5 -eq 05 ]] && echo "5 equals 05"
-ne -ne [[ 6 -ne 20 ]] && echo "6 is not equal to 20"

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

Powered by ComboStrap