Size: 4138
Comment:
|
Size: 4101
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
## page was renamed from ShellTests |
Shell Tests
In Unix shell scripting, the portable syntax for logic tests is:
if [ EXPR ]; then command fi
The [ is not a grammar, but a command--specifically an alias for test.
If using a higher-level shell, use their constructs. For example, in Bash, use [[ EXPR ]] (which is a grammar).
Variable Tests
Usage |
True if... |
var1 = var2 |
var1 is equivalent to var2 |
var1 != var2 |
var1 is not equivalent to var2 |
-z var |
string length of var is 0 |
-n var |
string length of var is not 0 |
var1 -eq var2 |
var1 is numerically equal to var2 |
var1 -ne var2 |
var1 is numerically inequal to var2 |
var1 -gt var2 |
var1 is numerically greater than var2 |
var1 -ge var2 |
var1 is numerically greater than/ equal to to var2 |
var1 -lt var2 |
var1 is numerically lesser than var2 |
var1 -le var2 |
var1 is numerically lesser than/ equal to to var2 |
Caveats and Warnings
It is absolutely critical for variables to be quoted within tests, because they are evaluated by the shell. Even so, if any variables can be set to an empty string (or unset), these tests can suffer from instability. For example, "$var" = foo could evaluate to = foo, which would raise an error since the = operator requires values on either side. The common workaround is prefixing with an arbitrary letter, typically "x".
In summary:
# bad if [ $var = foo ]; then command fi # good if [ x"$var" = "xfoo" ]; then command fi
File Tests
These are probably what you are looking for.
Usage |
True if... |
-d fn |
directory exists |
-e fn |
file exists |
These rarely are useful.
Usage |
True if... |
-b fn |
file exists and is a block special file |
-c fn |
file exists and is a character special file |
-f fn |
file exists and is a regular file |
-g fn |
file exists and its set-group-id bit is set |
-h fn |
symbolic link exists (same as -L) |
-p fn |
named pipe (FIFO) exists |
-r fn |
file exists and is readable |
-s fn |
file exists and its size is greater than zero |
-t fn |
file descriptor is open and refers to a terminal |
-u fn |
file exists and its set-user-id bit is set |
-w fn |
file exists and is writable |
-x fn |
file exists and is executable |
-L fn |
symbolic link exists (same as -h) |
-S fn |
socket exists |
fn1 -ef fn2 |
fn1 has same device and inode numbers as fn2 |
fn1 -nt fn2 |
fn1 is newer (modification date) than fn2 |
fn1 -ot fn2 |
fn1 is older (modification date) than fn2 |
Compound Logic
To negate a test, insert ! before the expression.
if [ ! EXPR ]; then command fi
The test command supports options for AND and OR operations (-a and -o respectively). Do not use these. Instead, consider a less ambiguous grammar construct.
if [ EXPR ] && [ EXPR ]; then command fi if [ EXPR ] || [ EXPR ]; then command fi