如何比较Bourne Shell中的字符串?

n-a*_*der 12 shell posix sh

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

var1="mtu eth0"

if [ "$var1" == "mtu *" ]
then
    # do something
fi
Run Code Online (Sandbox Code Playgroud)

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

mst*_*obl 18

使用Unix工具.该程序cut将愉快地缩短字符串.

if [ "$(echo $var1 | cut -c 4)" = "mtu " ];
Run Code Online (Sandbox Code Playgroud)

......应该做你想做的事.


eph*_*ent 11

bash

最短的修复:

if [[ "$var1" = "mtu "* ]]
Run Code Online (Sandbox Code Playgroud)

Bash [[ ]]不会得到全局扩展,不像[ ](由于历史原因必须).


bash --posix

哦,我发帖太快了.Bourne shell,不是Bash ......

if [ "${var1:0:4}" == "mtu " ]
Run Code Online (Sandbox Code Playgroud)

${var1:0:4}意思是前四个字符$var1.


/bin/sh

啊,对不起 Bash的POSIX仿真还远远不够; 一个真正的原始Bourne shell没有${var1:0:4}.你需要像mstrobl的解决方案.

if [ "$(echo "$var1" | cut -c0-4)" == "mtu " ]
Run Code Online (Sandbox Code Playgroud)

  • 我的 cut 版本说位置从 1 开始编号。 ``cut -c 1-4`` 或 ``cut -c -4`` 在这里返回正确的值。 (2认同)
  • bourne/posix shell 中没有 == 运算符;是`=`。 (2认同)

has*_*seg 6

您可以调用expr以匹配Bourne Shell脚本中的正则表达式的字符串.以下似乎有效:

#!/bin/sh

var1="mtu eth0"

if [ "`expr \"$var1\" : \"mtu .*\"`" != "0" ];then
  echo "match"
fi
Run Code Online (Sandbox Code Playgroud)