bash : Illegal number

2019-01-03 00:27发布

When I run this bash script :

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 ?

标签: bash shell
3条回答
迷人小祖宗
2楼-- · 2019-01-03 00:58

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

if [ "$EUID" -ne 0 ];

OR using [[ and ]]

if [[ "$EUID" -ne 0 ]];
查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-03 01:02

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.

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

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

would be a good way to do it.

查看更多
别忘想泡老子
4楼-- · 2019-01-03 01:06

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

if [ "$EUID" -ne 0 ];

OR using [[ and ]]

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 :

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

Instead of the external command test or his fork [ :

[ ~/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 
查看更多
登录 后发表回答