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 if string1 is identical to string2
  • if [$string1 != $string2]: This checks if string1 is not identical to string2
  • if [$string1 \< $string2]: This checks if string1 is less than string2
  • if [$string1 \> $string2]: This checks if string1 is greater than string2

The less than and greater than should be escaped with a backslash as if it shows a warning.

  • if [-n $string1]: This checks if string1 is longer than zero
  • if [-z $string1]: This checks if string1 has zero length

Let's see some examples to explain how if statements work:

#!/bin/bash if [ "mokhtar" = "Mokhtar" ] then echo "Strings ...

Get Mastering Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.