String comparison

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Numeric comparisonHomeFile attributes comparisons →

String comparison can be done using test command itself.

The strings are equal

Use the following syntax:

STRING1 = STRING2

Example

#!/bin/bash
read -s -p "Enter your password " pass
echo 
if test "$pass" = "tom"
then
    echo "You are allowed to login!"
fi

The strings are not equal

Use the following syntax:

STRING1 != STRING2

Example

#!/bin/bash
read -s -p "Enter your password " pass
echo 
if test "$pass" != "tom"
then
    echo "Wrong password!"
fi

The length of STRING is zero

Use the following syntax (this is useful to see if variable is empty or not):

-z STRING

Example

#!/bin/bash
read -s -p "Enter your password " pass
echo 
if test -z $pass 
then
    echo "No password was entered!!! Cannot verify an empty password!!!"	
    exit 1
fi
if test "$pass" != "tom"
then
    echo "Wrong password!"
fi
← Numeric comparisonHomeFile attributes comparisons →