Bash – How to exit a script in a conditional statement

bashscriptingshellshell-script

I'm writing a bash script where I want to exit if the user is not root. The conditional works fine, but the script does not exit.

[[ `id -u` == 0 ]] || (echo "Must be root to run script"; exit)

I've tried using && instead of ; but neither work.

Best Answer

You could do that this way:

[[ $(id -u) -eq 0 ]] || { echo >&2 "Must be root to run script"; exit 1; }

("ordinary" conditional expression with an arithmetic binary operator in the first statement), or:

(( $(id -u) == 0 )) || { echo >&2 "Must be root to run script"; exit 1; }

(arithmetic evaluation for the first test).

Notice the change () -> {} - the curly brackets do not spawn a subshell. (Search man bash for "subshell".)