Книга: Fedora™ Unleashed, 2008 edition

String Comparison

String Comparison

The following operators can be used to compare two string expressions:

= — To compare whether two strings are equal

!= — To compare whether two strings are not equal

-n — To evaluate whether the string length is greater than zero

-z — To evaluate whether the string length is equal to zero

Next are some examples using these operators when comparing two strings, string1 and string2, in a shell program called compare1:

#!/bin/sh
string1="abc"
string2="abd"
if [ $string1 = $string2 ]; then
 echo "string1 equal to string2"
else
 echo "string1 not equal to string2"
fi
if [ $string2 != string1 ]; then
 echo "string2 not equal to string1"
else
 echo "string2 equal to string2"
fi
if [ $string1 ]; then
 echo "string1 is not empty"
else
 echo "string1 is empty"
fi
if [ -n $string2 ]; then
 echo "string2 has a length greater than zero"
else
 echo "string2 has length equal to zero"
fi
if [ -z $string1 ]; then
 echo "string1 has a length equal to zero"
else
 echo "string1 has a length greater than zero"
fi

If you execute compare1, you get the following result:

string1 not equal to string2
string2 not equal to string1
string1 is not empty
string2 has a length greater than zero
string1 has a length greater than zero

If two strings are not equal in size, the system pads out the shorter string with trailing spaces for comparison. That is, if the value of string1 is abc and that of string2 is ab, string2 will be padded with a trailing space for comparison purposes — it will have a value of ab.

Оглавление книги

Оглавление статьи/книги

Генерация: 0.043. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз