1

when I run the following script

#!/bin/sh
[ `whoami` == root ] || echo "must be run as root" 

I get the following error

./test.sh: 2: [: root: unexpected operator

How can I avoid that error?

draca
  • 1,319
  • 5
  • 16
  • 32

1 Answers1

6

While it might seem like the problem is not quoting the word root, your script does run without error on my machine, even without quoting it. So it seems your error depends on the shell implementation.

The problem is that sh is implemented by different shells in different environments. The posix sh command doesn't support == (only =), and I think that's the error you're experiencing. See e.g. this answer.

Try changing the first line to #!/bin/bash to see if this is the case on your machine.

avivr
  • 1,393
  • 15
  • 28
  • 1
    @draca, since you're using `[` not `[[`, you want to "quote all the things", so `[ "$(whoami)" = root ]` – glenn jackman Sep 01 '17 at 16:30
  • @draca, can you please accept the answer if it's correct? thanks – avivr Sep 03 '17 at 20:11
  • Had this issue in a dockerfile, worked just fine on Alpine, ubuntu on the other hand did not like it! Thanks for the answer ;) – Jite Oct 06 '19 at 15:25