shell脚本:期望的整数表达式

时间:2012-07-22 18:15:26

标签: bash shell

#!/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上运行上面的脚本时遇到错误。

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

您可以帮忙删除此错误吗?

2 个答案:

答案 0 :(得分: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?

答案 1 :(得分: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
相关问题