bash : 非法号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19597962/
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-10 00:21:51  来源:igfitidea点击:

bash : Illegal number

bashshell

提问by 4m1nh4j1

When I run this bash script :

当我运行这个 bash 脚本时:

if [ [$EUID -ne 0] ]; then
   echo "This script must be run as root" 1>&2 
   exit 1
else 

printf " whathever "

exit 0 
fi

I have this error :

我有这个错误:

./myScript: 15: [: Illegal number: [

Do you see any problem ?

你看有什么问题吗?

回答by anubhava

You have syntax error in your if condition, use this if condition:

您的 if 条件中有语法错误,请使用此 if 条件:

if [ "$EUID" -ne 0 ];

OR using [[and ]]

或使用[[]]

if [[ "$EUID" -ne 0 ]];

回答by jrrs

two suggestions apart from what everyone else has pointed out already.

除了其他人已经指出的两个建议。

1) rather than doing 'else [bunch of code because we are root] fi', just replace the 'else' with 'fi'. once you've tested for the failure condition you are concerned about and taken appropriate action, no need to continue to be within the body of the conditional.

1) 而不是做'else [一堆代码,因为我们是root] fi',只需将'else' 替换为'fi'。一旦您测试了您关心的失败条件并采取了适当的措施,就无需继续处于条件的主体内。

2) $EUID is a bashism, if you would like to make this portable to shells such as ksh, replacing it with:

2) $EUID 是一种 bashism,如果您想让它可移植到诸如 ksh 之类的 shell,请将其替换为:

if [ $(id -u) -ne 0 ]; then echo "ur not root bro"; exit 1; fi

如果 [ $(id -u) -ne 0 ]; 然后回声“你不是根兄弟”;出口1;菲

would be a good way to do it.

将是一个很好的方法来做到这一点。

回答by Idriss Neumann

You have syntax error in your if condition, use this if condition:

if [ "$EUID" -ne 0 ];

OR using [[and ]]

if [[ "$EUID" -ne 0 ]];

您的 if 条件中有语法错误,请使用此 if 条件:

if [ "$EUID" -ne 0 ];

或使用[[]]

if [[ "$EUID" -ne 0 ]];

If you use the KSH88+/Bash 3+ internal instruction [[, it's not necessary to use doubles quotes around the variables operands :

如果您使用 KSH88+/Bash 3+ 内部指令[[,则无需在变量操作数周围使用双引号:

[ ~/test]$ [[ $var2 = "string with spaces" ]] && echo "OK" || echo "KO" 
OK 

Instead of the external command testor his fork [:

而不是外部命令test或他的叉子[

[ ~/test]$ [ $var2 = "string with spaces" ] && echo "OK" || echo "KO" 
bash: [: too many arguments
KO 
[ ~/test]$ [ "$var2" = "string with spaces" ] && echo "OK" || echo "KO" 
OK 

Of course, you also have to choose the operators according to the type of operands :

当然,您还必须根据操作数的类型来选择运算符:

[ ~/test]$ var1="01" 
[ ~/test]$ [ "$var1" = "1" ] && echo "OK" || echo "KO" 
KO 
[ ~/test]$ [ "$var1" -eq "1" ] && echo "OK" || echo "KO" 
OK 

回答by Eswar Chitirala

using

使用

sudo bash shell_script.sh

sudo bash shell_script.sh

instead of

代替

sudo sh shell_script.sh

sudo sh shell_script.sh

solved in my case.

在我的情况下解决了。