My shell script is as shown below:
#!/bin/bash
# Make sure only root can run our script
[ $EUID -ne 0 ] && (echo "This script must be run as root" 1>&2) || (exit 1)
# other script continues here...
When I run above script with non-root user, it prints message “This script…” but it doe not exit there, it continues with the remaining script. What am I doing wrong?
Note: I don’t want to use if condition.
You’re running
echoandexitin subshells. The exit call will only leave that subshell, which is a bit pointless.Try with:
If for some reason you don’t want an
ifcondition, just use:Note: no
()and fixed boolean condition. Warning: ifechofails, that test will also fail to exit. Theifversion is safer (and more readable, easier to maintain IMO).