【原创】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基本运算符

  • 3
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值