OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

String Expressions

The following expressions are used to evaluate strings:


Table 27-2: test String Expressions


Expression Is True If...

Expression Is True If...

string string is not null.


image

-n string The length of string is greater than zero.


image

image

-z string The length of string is zero.

string1 = string2 string1 == string2

string1 and string2 are equal. Single or double equal signs may be used, but the use of double equal signs is greatly preferred.


image

image

image

image

string1 != string2 string1 and string2 are not equal. string1 > string2 string1 sorts after string2. string1 < string2 string1 sorts before string2.


image

Warning: the > and < expression operators must be quoted (or escaped with a backslash) when used with test. If they are not, they will be interpreted by the shell as redirection operators, with potentially destructive results. Also note that while the bash documentation states that the sorting order conforms to the colla- tion order of the current locale, it does not. ASCII (POSIX) order is used in ver- sions of bash up to and including 4.0.


image


Here is a script that incorporates string expressions:



#!/bin/bash


# test-string: evaluate the value of a string ANSWER=maybe

if [ -z "$ANSWER" ]; then

echo "There is no answer." >&2 exit 1

fi


if [ "$ANSWER" = "yes" ]; then echo "The answer is YES."

elif [ "$ANSWER" = "no" ]; then echo "The answer is NO."

elif [ "$ANSWER" = "maybe" ]; then echo "The answer is MAYBE."

else

echo "The answer is UNKNOWN."

fi

#!/bin/bash


# test-string: evaluate the value of a string ANSWER=maybe

if [ -z "$ANSWER" ]; then

echo "There is no answer." >&2 exit 1

fi


if [ "$ANSWER" = "yes" ]; then echo "The answer is YES."

elif [ "$ANSWER" = "no" ]; then echo "The answer is NO."

elif [ "$ANSWER" = "maybe" ]; then echo "The answer is MAYBE."

else

echo "The answer is UNKNOWN."

fi


In this script, we evaluate the constant ANSWER. We first determine if the string is empty. If it is, we terminate the script and set the exit status to one. Notice the redirection that is applied to the echo command. This redirects the error message “There is no answer.” to standard error, which is the proper thing to do with error messages. If the string is not empty, we evaluate the value of the string to see if it is equal to either “yes,” “no,” or “maybe.” We do this by using elif, which is short for “else if.” By using elif, we are able to construct a more complex logical test.


Top OS Cloud Computing at OnWorks: