Posts Tagged ‘condition’

[ … ] or test is the command used to test information about files.

e.g.:

$ [ -f file ] # true if file is an ordinary file
$ [ ! -f file ] # true if file is NOT an ordinary file
$ [ -d file ] # true if file is a directory
$ [ -u file ] # true if file has SUID permission
$ [ -g file ] # true if file has SGID permission
$ [ -x file ] # true if file exists and is executable
$ [ -r file ] # true if file exists and is readable
$ [ -w file ] # true if file exists and is writeable
$ [ file1 -nt file2 ] # true if file1 is newer than file2

Important Notes:
– Use spaces after the ‘[‘ and before the ‘]’.
– Use spaces around operators.

[ … ] or test is the built-in command for comparing string/integers in shell programming.

e.g.:

[ "$USER" = root ] # true if the value of $USER is "root"
[ "$USER" != root ] # true if the value of $USER is not "root"
[ -z "$USER" ] # true if the string "$USER" has zero length
[ string1 \ string2 ] # true if string1 sorts greater than string2

e.g.:

[ "$x" -eq 5 ] # true if the value of $x is 5
[ "$x" -ne 5 ] # true if integer $x is not 5
[ "$x" -lt 5 ] # true if integer $x is  5
[ "$x" -le 5 ] # true if integer $x is = 5
[ "$x" -ge 5 ] # true if integer $x is = 5

Important Notes:
– Use spaces after the ‘[‘ and before the ‘]’.
– Use spaces around operators.
– Quote special symbols.