Test command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Bash structured language constructsHomeif structures to execute code based on a condition →

The test command is used to check file types and compare values. Test is used in conditional execution. It is used for:

  • File attributes comparisons
  • Perform string comparisons.
  • Basic arithmetic comparisons.

test command syntax

test condition

OR

test condition && true-command

OR

test condition || false-command

OR

test condition && true-command || false-command

Type the following command at a shell prompt (is 5 greater than 2? ):

test 5 -gt 2 && echo "Yes"
test 1 -lt 2 && echo "Yes"

Sample Output:

Yes
Yes

You need to use the test command while making decisions. Try the following examples and note down its output:

test 5 -eq 5 && echo Yes || echo No
test 5 -eq 15 && echo Yes || echo No
test 5 -ne 10 && echo Yes || echo No
test -f /etc/resolv.conf && echo "File /etc/resolv.conf found." || echo "File /etc/resolv.conf not found."
test -f /etc/resolv1.conf && echo "File /etc/resolv1.conf found." || echo "File /etc/resolv1.conf not found."

See also

← Bash structured language constructsHomeif structures to execute code based on a condition →