Test command with the if command
You have seen how to use the test
command or the short version [ ]
. This test returns zero (true) or non-zero (false).
You will see how to check the returned result using the if
command.
Checking strings
You can use the if
command with the test
command to check if the string matches a specific criterion:
if [$string1 = $string2]
: This checks ifstring1
is identical tostring2
if [$string1 != $string2]
: This checks ifstring1
is not identical tostring2
if [$string1 \< $string2]
: This checks ifstring1
is less thanstring2
if [$string1 \> $string2]
: This checks ifstring1
is greater thanstring2
The less than and greater than should be escaped with a backslash as if it shows a warning.
if [-n $string1]
: This checks ifstring1
is longer than zeroif [-z $string1]
: This checks ifstring1
has zero length
Let's see some examples to explain how if
statements work:
#!/bin/bash if [ "mokhtar" = "Mokhtar" ] then echo "Strings are identical" else echo "Strings are not...