Shell编程-字符串运算符

时间:2020-02-23 14:45:09  来源:igfitidea点击:

在本教程中,我们将学习Shell编程中的字符串运算符。

在本教程中,我们将使用if else语句。

等于=

我们使用" ="等于运算符来检查两个字符串是否相等。

在下面的示例中,我们将检查输入的字符串是否相等。

#!/bin/sh

# take two strings from user
echo "Enter first string:"
read str1

echo "Enter second string:"
read str2

# check
if [ "$str1" = "$str2" ]
then
  echo "Strings are equal."
else
  echo "Strings are not equal."
fi
$sh equal.sh 
Enter first string:
Hello
Enter second string:
hello
Strings are not equal.

$sh equal.sh 
Enter first string:
Hello
Enter second string:
Hello
Strings are equal.

注意!我们将str1和str2括在双引号中,例如[" $str1" =" $str2"]以处理多字字符串。

不等于!=

我们使用"!="不等于运算符来检查两个字符串是否相等。

在下面的示例中,我们将检查输入的字符串是否不等于" Hello World"。

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

s="Hello World"

# check
if [ "$str" != "$s" ]
then
  echo "$str not equal to $s."
else
  echo "$str equal to $s."
fi
$sh notequal.sh 
Enter string:
Hello
Hello not equal to Hello World.

$sh notequal.sh 
Enter string:
Hello World
Hello World equal to Hello World.

-z检查大小为零

我们使用-z检查字符串的大小是否为零。

在下面的示例中,我们将检查输入的字符串的大小是否为零。

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

# check
if [ -z "$str" ]
then
  echo "String size equal to 0."
else
  echo "String size not equal to 0."
fi
$sh zerosize.sh 
Enter string:
Hello World
String size equal to 0.

$sh zerosize.sh 
Enter string:

String size equal to 0.

-n检查大小不为零

我们使用-n检查字符串的大小是否不为零。

在下面的示例中,我们将检查输入的字符串的大小是否不为零。

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

# check
if [ -n "$str" ]
then
  echo "String size not equal to 0."
else
  echo "String size equal to 0."
fi
$sh notzerosize.sh 
Enter string:
Hello
String size not equal to 0.

$sh notzerosize.sh 
Enter string:

String size equal to 0.

${#str}查找字符串的长度

在下面的示例中,我们将打印输入字符串的长度。

#!/bin/sh

# take a string from user
echo "Enter string:"
read str

echo "Length of the entered string = ${#str}"
$sh length.sh 
Enter string:

Length of the entered string = 0

$sh length.sh 
Enter string:
Hello
Length of the entered string = 5

$sh length.sh 
Enter string:
Hello World
Length of the entered string = 11