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?

1
  • 1
    [ `whoami` == "root" ] || echo "must be root" Commented Sep 1, 2017 at 13:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@draca, since you're using [ not [[, you want to "quote all the things", so [ "$(whoami)" = root ]
@draca, can you please accept the answer if it's correct? thanks
Had this issue in a dockerfile, worked just fine on Alpine, ubuntu on the other hand did not like it! Thanks for the answer ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.