下面是简单的脚本,运行脚本时我收到第 10 行异常:语法错误:文件意外结束。请帮忙。
#!/bin/sh
a=10
b=20
if [ 10 == 20 ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
答案1
首先,我认为[ 10 == 20 ]
是拼写错误,应该是[ "$a" == "$b" ]
。其次@dsstorefile1是对的在 POSIX sh 中,不支持 ==。
如果你使用过,shellcheck
你可以自己发现这一点:
$ shellcheck script.sh
In script.sh line 4:
if [ "$a" == "$b" ]
^-- SC2039: In POSIX sh, == is not supported.
这是脚本的稍高级版本,可以处理前两个位置参数:
#!/bin/sh
a="$1"
b="$2"
if [ "$a" = "$b" ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
然后你可以这样使用它:
$ ./script.sh 10 20
a is not equal to b
$ ./script.sh 10 10
a is equal to b
答案2
改成:==
-eq
#!/bin/sh
a=10
b=20
if [ 10 -eq 20 ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
顺便说一句:您已设置变量 a 和 b,但并未使用它们。我想您的意图是:
#!/bin/sh
a=10
b=20
if [ $a -eq $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
看看man test
中的表达式是什么样[ ]
的。=
用于字符串比较,,-eq
等-gt
用于整数比较。