James's Ramblings

Bash: Conditionals

Created: May 15, 2020

Bash Manuals: Conditionals

Maths

Description Command
Equal to. -eq
Not equal to. -ne
Less than. -lt
Less than or equal to. -le
Greater than. -gt
Greater than or equal to. -ge

Strings

Description Command
True if the length of STRING is non-zero. STRING or -n STRING
True if the length of STRING is zero. -z STRING
True if STRING1 equals STRING2. POSIX conformant. STRING1 = STRING2
True if STRING1 equals STRING2. STRING1 == STRNG2
True if STRING1 does not equal STRING2. STRING1 != STRING2
True if STRING1 sorts after STRING2 in the current locale.* STRING1 > STRING2
True if STRING1 sorts before STRING2 in the current locale.* STRING1 < STRING2

* Careful with quoting.

Variables

Description Command
True if the variable VAR_NAME has been assigned a value. -v VAR_NAME
True if the variable VAR_NAME is set and is a name reference. -R VAR_NAME

Logic Inversion

Description Command
Invert the result of CONDITION. ! CONDITION

Files: Basic & Types

Description Command
True if FILE exists. -a FILE or -e FILE
True is FILE exists and is a directory. -d FILE
True if FILE exists and is a regular file. -f FILE
True if FILE exists and is a symbolic link. -h FILE or -L FILE
True if FILE exists and has size greater than zero. -s FILE

Files: RWX

Description Command
True if FILE exists is readable. -r FILE
True if FILE exists and is writable. -w FILE
True if FILE exists and is executable. -x FILE

Files: Fourth Permission Octal

Description Command
True if FILE exists and its GID bit is set. -g FILE
True if FILE exists and its sticky bit is set. -k FILE
True if FILE exists and its UID bit is set. -u FILE
True if FILE exists and is owned by the effective group ID. -G FILE
True if FILE exists and is owned by the effective user ID. -O FILE

Files: Advanced

Description Command
True if FILE exists and is a block special file. -b FILE
True if FILE exists and is a character special file. -c FILE
True if FILE exists and is a named pipe (FIFO). -p FILE
True if file descriptor FD is open and refers to a terminal. -t FD
True if FILE exists and has been modified since it was last read. -N FILE
True if FILE exists and is a socket. -S FILE

* This can be used to test whether input is coming from a STDIN/a terminal (-t 0), or from a file or pipe.

Files: Comparison

Description Command
True if FILE1 and FILE2 refer to the same device and inode numbers. FILE1 -ef FILE2
True if FILE1 is newer than FILE2, or if FILE1 exists and FILE2 does not. FILE -nt FILE2
True if FILE1 is older than FILE2, or if FILE2 exists and FILE1 does not. FILE1 -ot FILE2