2

I have a bash script that will only work with root privileges, so I want to test whether the user has them. Other posts (see below) ask and answer how to know whether the user is actually running as root, but not whether the script has root privileges. These posts say to test whether $EUID is 0.

To try this idea in the context of sudo, I wrote a bash script /tmp/a.sh:

#!/bin/bash
echo $EUID

The following two commands were run as a non-root user with sudo privileges on Ubuntu 16.04. If the $EUID suggestion worked in the context of sudo, the second command would have printed 0 instead of a blank line.

$ /tmp/a.sh
1000
$ sudo /tmp/a.sh

$ 

FYI, an example of the related posts I am referencing is:

How can a script check if it's being run as root?

2 Answers2

1

The script /tmp/a.sh only works with #!/bin/bash on the first line. When actually running the example I gave, the ! was accidentally omitted and the only user reported was the non-root user as shown in the question.

0

I use the following in some of my scripts:

#!/bin/bash

if [ "$(id -un)" != "root" ]; then
    echo "Need root - sudoing..."
    exec sudo "$0" "$@"
fi
# Now we are root

Ralf
  • 256