Shell script continues to run even after exit command
You're running echo
and exit
in subshells. The exit call will only leave that subshell, which is a bit pointless.
Try with:
#! /bin/shif [ $EUID -ne 0 ] ; then echo "This script must be run as root" 1>&2 exit 1fiecho hello
If for some reason you don't want an if
condition, just use:
#! /bin/sh[ $EUID -ne 0 ] && echo "This script must be run as root" 1>&2 && exit 1echo hello
Note: no ()
and fixed boolean condition. Warning: if echo
fails, that test will also fail to exit. The if
version is safer (and more readable, easier to maintain IMO).
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:
#!/bin/bash[ $1 -ne 0 ] && (echo "This script must be run as root." 1>&2) && exit 1echo Continuing...
Running this with ./myscript 0
gives you:
Continuing...
while ./myscript 1
gives you:
This script must be run as root.
I believe that's what you were looking for.