📌  相关文章
📜  用于检查特定条件的字符串的 Shell 脚本

📅  最后修改于: 2022-05-13 01:57:33.193000             🧑  作者: Mango

用于检查特定条件的字符串的 Shell 脚本

在这里,我们将编写一个 shell 脚本,如果接受的字符串不满足特定条件,它将回显(打印)一条合适的消息。假设我们给出了一些特定条件,那么我们的任务是在接受的字符串与条件不匹配时打印消息。

示例 1:

如果接受的字符串长度小于 10,我们将显示一条消息“字符串太短”。

Input:  "abcdef"
Output:  String is too short
Length is 6, which is smaller than 10.

方法:

  • 我们将从用户那里获取一个字符串
  • 我们必须找到字符串的长度,以便我们可以决定它是小于还是大于 10。
  • 我们将使用以下命令找到长度:
len=`echo -n $str | wc -c`

下面是实现:



# Shell script to print message 
# when condition doesn't matched

# taking user input
echo "Enter the String : "
read string

# Finding the length of string 
# -n flag to avoid new line
# wc -c count the chars in a file
len=`echo -n $string | wc -c`

# Checking if length is smaller
# than 10 or not
if [ $len -lt 10 ]
    then
        # if length is smaller 
        # print this message
        echo "String is too short."
fi

输出:

示例 2:我们将接受两个输入字符串并查找两者是否相等。

下面是实现:

# Shell script to check whether two 
# input strings is equal

# take user input
echo "Enter string a : "
read a

echo "Enter string b : "
read b

# check equality of input
if [ "$a" = "$b" ]; then

    # if equal print equal
    echo "Strings are equal."
else
      # if not equal
    echo "Strings are not equal."
fi

输出:

Geeks
Geeks
Strings are equal.

示例 3:

我们正在处理字符串,所以现在我们将把两个字符串作为输入,并检查这两个字符串中哪一个在词典(字母)顺序方面更大

# Shell script to check which 
# string is lexicographiclly
# larger

# user input
echo "Enter String a : "
read a

echo "Enter String b : "
read b

# if a is greater than b
if [[ "$a" > "$b" ]]; then
    echo "${a} is lexicographically greater then ${b}."

# if b is greater than a
elif [[ "$a" < "$b" ]]; then
    echo "${b} is lexicographically greater than ${a}."

# if both are equal
else
    echo "Strings are equal"
fi

输出:

abc
def
def is lexicographically greater than abc.