Bash test: Difference between revisions
Jump to navigation
Jump to search
(→-e) |
(→-f) |
||
Line 17: | Line 17: | ||
[ ! -f ${file} ] && echo "we're not a file" || echo "we're a file" | [ ! -f ${file} ] && echo "we're not a file" || echo "we're a file" | ||
</pre> | </pre> | ||
=-e= | |||
True if file exists (regardless of type). | |||
=-f= | =-f= | ||
True if file exists and is a regular file. | |||
=-w= | =-w= |
Revision as of 23:45, 23 February 2018
External
Internal
Overview
'test' is a bash built-in command which tests the expression following it, according to the syntax described below. 'test' and [...] are synonymous and can be used interchangeably.
Negation
[ ! -f ${file} ] && echo "we're not a file" || echo "we're a file"
-e
True if file exists (regardless of type).
-f
True if file exists and is a regular file.
-w
True if file exists and is writable.
-h
Tests whether the file exists and it is a symbolic link.
[ -h $0 ] && echo "we're a link" || echo "we're not a link"
Integer Comparison
[arg1 -eq|-ne|-lt|-le|-gt|-ge arg2]
String Comparison
< and > can be used for string comparison, in ASCII alphabetical order, but
[[ ... ]]
must be used:
if [[ "${a}" > "${b}" ]]; them ... fi
-z, -n
-z: true if the length of the string is zero.
-n: true if the length of string is non-zero.
Can be used to check for undeclared variables
[ -z ${var} ] && echo" 'var' not declared"
- Quotation marks around the variables are needed, otherwise the expression will fail syntactically when the variable is declared and it contains a space:
var="a b" ... line 177: [: 900: binary operator expected
Combining test and Command Conditionals
Not sure if this belongs here, refactor with https://home.feodorov.com:9443/wiki/Wiki.jsp?page=bashConditionalConstructs
verbose=false if ! ${verbose} && [ "$1" = "--verbose" -o "$1" = "-v" ]; then echo "setting verbose to ON" fi
- Must have a space between ! and the command that evaluates to true or false.