尝试根据行是否以“!”开头来创建条件。
注意:这不是bash
#!/bin/sh
if [ $line = "!*" ] ;
then
echo "$0: $line has !"
else
echo "$0: $line has no !"
fi
答案 0 :(得分:3)
在POSIX test
中,=
仅执行完全字符串比较。
改为使用case
语句。
case $line in
"!"*) echo "$line starts with an exclamation mark" ;;
*) echo "$line does not start with an exclamation mark" ;;
esac
如果确实希望将其放在if
中,您可以这样做:
if case $string in "!"*) true;; *) false;; esac; then
echo "$line starts with an exclamation mark"
else
echo "$line does not start with an exclamation mark"
fi
答案 1 :(得分:1)
您可以使用标准的POSIX参数替换语法。
${var#repl}
将从repl
变量内容的开头删除$var
。
因此,您将拥有:
$ var=test
$ echo ${var#t}
est
$ echo ${var#X}
test
因此,为了有一个简单的if
语句来检查变量是否以字符串开头(在您的情况下为!
),您可以:
#!/bin/sh
if test "$line" = "${line#!}"; then
echo "$0: $line has no !"
else
echo "$0: $line has !"
fi
PS:test ...
等同于[ ... ]
,因此上述脚本与
#!/bin/sh
if [ "$line" = "${line#!}" ]; then
echo "$0: $line has no !"
else
echo "$0: $line has !"
fi
答案 2 :(得分:0)
可以像echo "$STR" | cut -c -1
一样简单。
#!/bin/sh
STR="!abcd"
if [ "!" = $(echo "$STR" | cut -c -1) ]; then
echo "true"
fi