Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active July 21, 2019 06:02
Show Gist options
  • Save estysdesu/f56a3e239ad291b36aa8926a714aed33 to your computer and use it in GitHub Desktop.
Save estysdesu/f56a3e239ad291b36aa8926a714aed33 to your computer and use it in GitHub Desktop.
[Shell: test conditionals] #test #conditionals
##### test OR [ -s/-n/-t/(etc...) ] (TEST CONDITIONALS) #####
# https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html
# numeric and string are different for numbers -- `test 01 -eq 1` is true, but `test "01" == "1"` is obviously not
# -f: file exists
# -s: file exists and has size > 0
# ! <-flag>: negate
# -d: directory exists
# -x: can execute
# <#> -eq <#>: numeric equality; good for exit codes
# <#> -ne <#>: numeric inequality (test if not equal)
# <stirng> = <string>: string equality (double == can be used also)
# <string> != <string>: string inequality
# -o: or condition
# -a: and
# -ge/-gt/-le/-lt/-nt/-ot: test file modification (newer than, greater than, etc)
test ! -f <file>
test -x `which <cmd>`
test 1 -eq "$?"
test ! “a” != “a” # double negative --> exit code is 0
test 1 –eq 1 –a 2 –eq 2
# "test" if <cmd> is present (from binary in PATH etc)
[ command -v <cmd> &> /dev/null] && <do-something>
if (command -v <cmd> &> /dev/null); then #posix
<do-something>
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment