How do I exit a script in a conditional statement?
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".)
The parentheses around those commands creates a subshell. Your subshell echos "Must be root to run script" and then you tell the subshell to exit (although it would've already, since there were no more commands). The easiest way to fix it is probably to just use an if
:
if [[ `id -u` != 0 ]]; then
echo "Must be root to run script"
exit
fi
With bash:
[ $UID -ne 0 ] && echo "Must be root to run script" && exit 1