2012-07-22 414 views
0
#!/bin/bash 
if [$# -ne 1]; 
then 
    echo "/root/script.sh a|b" 
else if [$1 ='a']; 
then 
    echo "b" 
else if [$1 ='b']; then 
    echo "a" 
else 
    echo "/root/script.sh a|b" 
fi 

在Linux上面的脚本运行时出现错误。shell脚本:预期的整数表达式

bar.sh: line 2: [: S#: integer expression expected 
a 

您能否帮忙移除此错误?

+3

哎,我*希望你没有在root帐户中练习你的shell脚本。 – zwol 2012-07-22 18:35:48

+1

在转录错误信息或代码时,错误信息中的'S#'看起来像拼写错误'$#'。 – tripleee 2012-07-22 19:03:59

回答

5
if [$# -ne 1]; 

[]需要间距。例如:

if [ $# -ne 1 ]; 

而且else if应该elif

#!/bin/bash 
if [ "$#" -ne 1 ]; 
then 
    echo "/root/script.sh a|b" 
elif [ "$1" ='a' ]; 
then 
    echo "b" 
elif [ "$1" ='b' ]; then 
    echo "a" 
else 
    echo "/root/script.sh a|b" 
fi 

不要忘记引用变量。这不是每次都需要,但建议。

问题:为什么我有-1?

+0

''''''后面的分号只有在将'then'放在同一行时才是必需的。 – zwol 2012-07-22 18:32:43

+0

我知道,但这没有问题,所以我没有改变它。 – Rayne 2012-07-22 18:34:29

+1

Doh!我没有注意到原来的剧本是如此。 – zwol 2012-07-22 18:34:49

2

Bash不允许else if。相反,请使用elif

此外,您需要在[...]表达式中的间距。

#!/bin/bash 
if [ $# -ne 1 ]; 
then 
    echo "/root/script.sh a|b" 
elif [ $1 ='a' ]; 
then 
    echo "b" 
elif [ $1 ='b' ]; then 
    echo "a" 
else 
    echo "/root/script.sh a|b" 
fi