Bash - If condition statement

By xngo on June 17, 2019

NOTE: Spacing is very important in 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

Testing file options

-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

Reference

  • http://tille.garrels.be/training/bash/ch07.html
  • http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html#tab_07_01 (Table of primary operators)
  • http://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html

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.