bash : Illegal number

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 ?


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

if [ "$EUID" -ne 0 ];

OR using [[ and ]]

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

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 

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.


using

sudo bash shell_script.sh

instead of

sudo sh shell_script.sh

solved in my case.