bash shell 脚本:预期的整数表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11602784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:51:21  来源:igfitidea点击:

shell script: integer expression expected

bashshell

提问by Shailendra Rajput

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

I'm getting below error while run above script in Linux.

在 Linux 中运行上述脚本时出现以下错误。

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

Could you please help to remove this error?

你能帮忙消除这个错误吗?

回答by Rayne

if [$# -ne 1];

[and ]requires spacing. Example:

[并且]需要间距。例子:

if [ $# -ne 1 ];

And else ifshould be elif

并且else if应该是elif

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

Do not forget to quote variables. It is not every time necessary, but recommended.

不要忘记引用变量。并非每次都需要,但建议这样做。

Question: Why do i have -1?

问题:为什么我有-1?

回答by chrisaycock

Bash doesn't allow else if. Instead, use elif.

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

Also, you need spacing within your [...]expression.

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

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