≡ Menu

Check if a Linux bash shell script is run as root

The question – I want my bash shell script to be run only as root. If another user tries to run the script, the script should terminate. Is there a way to do that in a shell script?

Bash has several environment variables that indicate which user is running the script:

[root@server ~]# echo $USER
root
[root@server ~]# echo $UID
0
[root@server ~]# id -u
0
[root@server ~]#

The $USER and $UID can be used to test whether the running user is indeed root.

The following script checks whether the command is run as root and terminates if it is not run by root:

#!/bin/bash
if [[ $UID -ne 0 ]]; then
    echo "This shell script($0) must be run as root!"
    exit 10
fi

The exit code could be anything other than 0 which signifies that the script terminated in a non-normal fashion.

The output of the script is as follows:

[root@server java]# ./root.sh
[root@server java]# su ewhathow
[ewhathow@server java]$ ./root.sh
This shell script(./root.sh) must be run as root!
[ewhathow@server java]$ exit
exit
[root@server java]# ./root.sh
[root@server java]#

Comments on this entry are closed.