如何在Bourne Shell中比较字符串? [英] How do I compare strings in Bourne Shell?

查看:93
本文介绍了如何在Bourne Shell中比较字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较shell中的字符串:

I need to compare strings in shell:

var1="mtu eth0"

if [ "$var1" == "mtu *" ]
then
    # do something
fi

但是显然"*"在Shell中不起作用.有办法吗?

But obviously the "*" doesn't work in Shell. Is there a way to do it?

推荐答案

bash

最短的修复方法:

bash

Shortest fix:

if [[ "$var1" = "mtu "* ]]

[ ]不同,Bash的[[ ]]不会进行全局扩展(出于历史原因,必须这样做).

Bash's [[ ]] doesn't get glob-expanded, unlike [ ] (which must, for historical reasons).

哦,我发布得太快了. Bourne外壳,不是Bash ...

Oh, I posted too fast. Bourne shell, not Bash...

if [ "${var1:0:4}" == "mtu " ]

${var1:0:4}表示$var1的前四个字符.

啊,对不起. Bash的POSIX仿真还远远不够.真正的原始Bourne外壳没有${var1:0:4}.您将需要类似mstrobl的解决方案.

Ah, sorry. Bash's POSIX emulation doesn't go far enough; a true original Bourne shell doesn't have ${var1:0:4}. You'll need something like mstrobl's solution.

if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]

这篇关于如何在Bourne Shell中比较字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆