Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active February 8, 2024 03:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save magnetikonline/5282716 to your computer and use it in GitHub Desktop.
Save magnetikonline/5282716 to your computer and use it in GitHub Desktop.
Bash if expressions cheatsheet.

Bash if expressions cheatsheet

Boolean
Is true *
VAR=:
if [[ $VAR ]]
Is false
VAR=
if [[ ! $VAR ]]
String
Is equal if [[ $VAR1 == $VAR2 ]]
Not equal if [[ $VAR1 != $VAR2 ]]
Is empty / zero length if [[ -z $VAR ]]
Not empty / non-zero length if [[ -n $VAR ]]
Less than (ASCII alpha) if [[ $VAR1 < $VAR2 ]]
Greater than (ASCII alpha) if [[ $VAR1 > $VAR2 ]]
Regular expression ** if [[ $VAR =~ ^my.+regexp$ ]]
Regular expression not ** if [[ ! $VAR =~ ^my.+regexp$ ]]
String contains *** if [[ $VAR =~ "needle" ]]
Integer
Is equal if [[ $VAR1 -eq $VAR2 ]]
Not equal if [[ $VAR1 -ne $VAR2 ]]
Less than if [[ $VAR1 -lt $VAR2 ]]
Less than or equal if [[ $VAR1 -le $VAR2 ]]
Greater than if [[ $VAR1 -gt $VAR2 ]]
Greater than or equal if [[ $VAR1 -ge $VAR2 ]]
File system
Is file (file, dir, symlink, anything) if [[ -e $FILE_PATH ]]
Is regular file if [[ -f $FILE_PATH ]]
Is regular file, is readable if [[ -r $FILE_PATH ]]
Is regular file, is writable if [[ -w $FILE_PATH ]]
Is regular file, is executable if [[ -x $FILE_PATH ]]
Is regular file, not zero size if [[ -s $FILE_PATH ]]
Is directory if [[ -d $FILE_PATH ]]
Is symlink if [[ -h $FILE_PATH ]]
Is socket if [[ -S $FILE_PATH ]]
File compare modification/exists
Is FILE1 newer than FILE2
...or FILE1 exists and FILE2 does not
if [[ $FILE1 -nt $FILE2 ]]
Is FILE1 older than FILE2
...or FILE2 exists and FILE1 does not
if [[ $FILE1 -ot $FILE2 ]]
Combine expressions
If EXPR1 and EXPR2 are true if [[ (EXPR1) && (EXPR2) ]]
If EXPR1 and EXPR2 are true if [ (EXPR1) -a (EXPR2) ]
If EXPR1 or EXPR2 are true if [[ (EXPR1) || (EXPR2) ]]
If EXPR1 or EXPR2 are true if [ (EXPR1) -o (EXPR2) ]

Notes

  • *: Use of : here as a NOP operation, which will always return true.
  • **: Regular expression captures available via array ${BASH_REMATCH[*]}, ${BASH_REMATCH[1]}, etc.
  • ***: This behavior for the =~ operator was introduced between Bash 3.1 -> 3.2.

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment