【原创】Shell中判断两个字符串是否相等

注:本文使用的是VMware Workstation 15 Player

1.使用Vi/Vim命令创建.sh文件并编写内容

使用Vi/Vim命令创建test.sh文件

[root@localhost ~]# vim test.sh

点击i键从命令模式转到输入模式,输入内容:

法1:使用“ = ”进行对比,注意字符串要与“=”之间留有 空格
注意:若无空格,则是用于赋值

#!/bin/bash

:<<EOF
author:zheng
time:2019.11.27
EOF

string1="str1"
string2="str2"

if test $string1 = $string2
then
    echo "string1 is equal to string2"
else
    echo "string1 is not equal to string2"
fi

法2:使用“ == ”进行对比,注意字符串要与“==”之间留有 空格

#!/bin/bash

:<<EOF
author:zheng
time:2019.11.27
EOF

string1="str1"
string2="str2"

if test $string1 == $string2
then
    echo "string1 is equal to string2"
else
    echo "string1 is not equal to string2"
fi

点击Esc按键从输入模式退出到命令模式,再输入:wq,保存并退出

:wq

2.为test.sh文件赋可执行权利

[root@localhost ~]# chmod +x test.sh

3.执行test.sh文件查看结果

输入:

[root@localhost ~]# ./test.sh

结果:

string1 is not equal to string2

总结:Linux中可用“ = ”或者“ == ”对两个字符串进行内容是否相等的判断,但是字符串与这两个运算符之间都应该要留有空格;若没有空格则译为赋值,这样if语句始终为true,始终输出的都是string1 is equal to string2

菜鸟教程 | Shell基本运算符


版权声明:本文为Z_Y_P12345678原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。