Bash Using Test

  • Read
  • Discuss

The test command in bash is used to evaluate a conditional expression and return an exit status of either 0 (true) or 1 (false). It is equivalent to the square bracket notation [ … ] and can be used as follows:

if test condition; then
  # code to be executed if condition is true
else
  # code to be executed if condition is false
fi

Here are some examples of conditions that can be tested using test:

  • File properties:
test -e file_name # true if file exists
test -f file_name # true if file exists and is a regular file
test -d directory_name # true if directory exists and is a directory

String comparison:

test string1 = string2 # true if string1 is equal to string2
test string1 != string2 # true if string1 is not equal to string2

Integer comparison:

test integer1 -eq integer2 # true if integer1 is equal to integer2
test integer1 -ne integer2 # true if integer1 is not equal to integer2
test integer1 -lt integer2 # true if integer1 is less than integer2
test integer1 -le integer2 # true if integer1 is less than or equal to integer2
test integer1 -gt integer2 # true if integer1 is greater than integer2
test integer1 -ge integer2 # true if integer1 is greater than or equal to integer2

Note that test is a built-in shell command and does not require an external executable.

Leave a Reply

Scroll to Top