test command in UNIX
test EXPRESSIONtest[ EXPRESSION ][ ][ OPTION
Introduction
Section titled “Introduction”test
command checks file types and compare values.
Options
Section titled “Options”Here are some of the options that you will use the most for string and variables:
( EXPRESSION )
:EXPRESSION
istrue
! EXPRESSION
:EXPRESSION
isfalse
-n STRING
: the length ofSTRING
is nonzero-z STRING
: the length ofSTRING
is zeroSTR1 = STR2
: the strings are equalSTR1 != STR2
: the strings are not equalINT1 -eq INT2
:INT1
is equal toINT2
INT1 -ge INT2
:INT1
is greater than or equal toINT2
INT1 -gt INT2
:INT1
is greater thanINT2
INT1 -le INT2
:INT1
is less than or equal toINT2
INT1 -lt INT2
:INT1
is less thanINT2
INT1 -ne INT2
:INT1
is not equal toINT2
Here are some of the options that you will use the most for files:
-e FILE
: file exists-d FILE
: file exists and is a directory-f FILE
: file exists and is a regular fileFILE1 -nt FILE2
:FILE1
is newer thanFILE2
(by modification date)FILE1 -ot FILE2
:FILE1
is older thanFILE2
-s FILE
: file exists and has a size greater than zero-r FILE
: file exists and read permission is granted-w FILE
: file exists and write permission is granted-x FILE
: file exists and execute (or search) permission is granted
Examples
Section titled “Examples”Variable comparison
Section titled “Variable comparison”$?
stores integer value returned by the last executed command.
The semicolon ;
separates multiple commands written on the same line.
test
command for variables values comparison works in this way:
#x="a"; y="a"; test "$x" = "$y"echo $?0 # no problems occurred
x="a"; y="b"; test "$x" = "$y";echo $?1 # a problem occurred: $x and $y are not equal
Quotes
Section titled “Quotes”Manual reference: