Chapter 9: Conditional Logic

if - else Statement

Below is the syntax:

1 if [[ condition ]]; then
2 	code
3 elif [[ condition ]]; then
4 	code
5 else
6 	code
7 fi
  • There must be a space between the opening and closing brackets and the condition you write. Otherwise, the shell will complain of error.
  • There must be space before and after the conditional operator (=, ==, <= etc). Otherwise, you’ll see an error like "unary operator expected".

Useful Unary Operators

Below are useful unary operators we can use with if statements:

Unary Operator Description
-e file_name True if file exists
-d dir_name True if specified directory exists
-h file_name True if the file exists & is a symlink
-s file_name True if file exists and size > 0
-r file_name True if file exists and is readable
-w file_name True if file exists and is writable
-x file_name True if file exists and is executable
-v var_name True if variable is set (even if it has an empty value
-z string_var True if length of string is zero
-n string_var True if length of string is non-zero

Avoiding if-else Statements

Operator Behavior    
; Allows you to chain commands together. It will run all commands regardless of whether they succeeded or failed.    
&& Similar to semicolon, but next command runs ONLY IF previous command succeeded    
      Next command is run ONLY IF previous command did NOT succeed
& All the above (;, &&,   ) will wait for execution of first command, then run 2nd command and so on. However, & will start the execution of first command and then it will start the execution of 2nd command, regardless of whether execution of first command was completed or not.
-z “$var_name” Checks if the variable is set to nothing. Equivalent code would be “$my_var” = “”    
[ -z “$my_var” ] This is an implicit if statement - you don’t need if, then, else, fi etc.    
1 # Using if-else
2 if [ "$EDITOR" = "" ]; then
3 	EDITOR=nano
4 fi
5 
6 # Not using if-else
7 [ -z "$EDITOR" ] && EDITOR=nano