Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script continues to run even after exit command

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.

like image 629
Mike Avatar asked Oct 16 '25 15:10

Mike


2 Answers

You're running echo and exit in subshells. The exit call will only leave that subshell, which is a bit pointless.

Try with:

#! /bin/sh
if [ $EUID -ne 0 ] ; then
    echo "This script must be run as root" 1>&2
    exit 1
fi
echo 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 1
echo 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).

like image 157
Mat Avatar answered Oct 18 '25 15:10

Mat


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 1
echo 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.

like image 39
paxdiablo Avatar answered Oct 18 '25 14:10

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!