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
echo
andexit
in 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
if
condition, just use:Note: no
()
and fixed boolean condition. Warning: ifecho
fails, that test will also fail to exit. Theif
version is safer (and more readable, easier to maintain IMO).I would write that as:
Using
{ }
for grouping, which executes in the current shell. Note that the spaces around the braces and the ending semi-colon are required.I think you need
&&
rather than||
, since you want to echo and exit (not echo or exit).In addition
(exit 1)
will run a sub-shell that exits rather than exiting your current shell.The following script shows what you need:
Running this with
./myscript 0
gives you:while
./myscript 1
gives you:I believe that's what you were looking for.