Bash conditional statements

By xngo on February 21, 2019

NOTE: Spacing is very important on the IF statement line.

IF syntax

#!/bin/bash
if [ true ]; then
  echo "Always true"
fi
# -------------------- OR --------------------
# You can also move then down as follows.
if [ 1 ]
then
  echo "Always true"
fi


IF else syntax

#!/bin/bash
str_1="String 1"
str_2="String 2"
if [ "$str_1" = "$str_2" ]; then
  echo "Both strings are equal."
else
  echo "Both strings are not equal."
fi

Check file existence

# If file exists
if [ -f testfile ]
then
  echo testfile exists!
fi
 
# If file doesn't exist
if [ ! -f /tmp/foo.txt ]; then
  echo "File not found!"
fi
 
# For directory, us -d instead of -f.

Check for missing arguments

# If no argument, display error message and exit script.
if [ $# -eq 0 ]; then
  echo "ERROR: Year argument is missing! Supply year argument to the batch file."
  exit 1;
fi

IF condition using return value of commands

# Don't encapsulate IF condition within []
if echo `uname -m` | grep -q "x86_64" 
then
  echo "64-bit"
else
  echo "32-bit"  
fi
Bash File Testing
 
-b filename - Block special file
-c filename - Special character file
-d directoryname - Check for directory existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID.
-g filename - true if file exists and is set-group-id.
-k filename - Sticky bit
-L filename - Symbolic link
-n string is not null
-O filename - True if file exists and is owned by the effective user id.
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable
 
http://www.tldp.org/LDP/abs/html/fto.html
http://www.tldp.org/LDP/abs/html/ops.html

Expressions table: TODO

Reference

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.