test command in UNIX


test EXPRESSION
test
[ EXPRESSION ]
[ ]
[ OPTION

Introduction

test command checks file types and compare values.

Options

Here are some of the options that you will use the most for string and variables:

  • ( EXPRESSION ): EXPRESSION is true
  • ! EXPRESSION: EXPRESSION is false
  • -n STRING: the length of STRING is nonzero
  • -z STRING: the length of STRING is zero
  • STR1 = STR2: the strings are equal
  • STR1 != STR2: the strings are not equal
  • INT1 -eq INT2: INT1 is equal to INT2
  • INT1 -ge INT2: INT1 is greater than or equal to INT2
  • INT1 -gt INT2: INT1 is greater than INT2
  • INT1 -le INT2: INT1 is less than or equal to INT2
  • INT1 -lt INT2: INT1 is less than INT2
  • INT1 -ne INT2: INT1 is not equal to INT2

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 file
  • FILE1 -nt FILE2: FILE1 is newer than FILE2 (by modification date)
  • FILE1 -ot FILE2: FILE1 is older than FILE2
  • -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

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

Manual reference: