170

I'm writing a simple bash script, but I need it to check whether it's being run as root or not. I know there's probably a very simple way to do that, but I have no idea how.

Just to be clear:
What's a simple way to write a script foo.sh, so that the command ./foo.sh outputs 0, and the command sudo ./foo.sh outputs 1?

0

11 Answers 11

227
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi
11
  • 7
    I'm accepting this one cause (after some testing) using the system variable EUID turned out to be (approx 100 times) faster than running a command (id -u), but all of the answers worked great.
    – Malabarba
    Dec 2, 2010 at 11:59
  • 24
    Also, $UID and $EUID are bashisms. Merely POSIX compliant shells don't have those variables and you need to use id(1) instead. Oct 16, 2014 at 9:28
  • 5
    in a bash script, you could use if ((EUID)); then, see @geirha's comment
    – jfs
    Oct 17, 2014 at 19:38
  • 9
    @Andrew: Variables are substituted before they are passed to sudo. If you run sudo sh -c 'echo $EUID' you will see your expected results. Nov 19, 2015 at 18:09
  • 8
    @Andrew – I know I'm way late here, but for posterity: $EUID is a Bashism (as mentioned above by @DavidFoerster), and your /bin/sh is most likely a link to /bin/dash, not /bin/bash. sudo bash -c 'echo $EUID' will yield the expected result. May 9, 2017 at 21:40
154

A root user does not have to be named "root". whoami returns the first username with user ID 0. $USER contains the name of the logged in user, which can have user ID 0, but have a different name.

The only reliable program to check whether the account is logged in as root, or not:

id -u

I use -u for the effective user ID, not -r for the real user ID. Permissions are determined by the effective user ID, not the real one.

Tests

/etc/passwd contains the following usernames with user ID 0 in the given order:

rootx
root2

Logged in as root2, gives the next results:

  • whoami: rootx
  • echo $USER: root2 (this returns an empty string if the program was started in an empty environment, e.g. env -i sh -c 'echo $USER')
  • id -u: 0 As you can see, the other programs failed in this check, only id -u passed.

The updated script would looks like this:

#!/bin/bash
if ! [ $(id -u) = 0 ]; then
   echo "I am not root!"
   exit 1
fi
6
  • 5
    I always try to stay as POSIX compliant as possible, using sh (dash) as interpreter instead of bash. But good shot, saves another fork :)
    – Lekensteyn
    Mar 13, 2011 at 10:34
  • After being out cold for a while, i came back and took a look. Lekensteyn's method does indeed seem to be better. His answer is now the new accepted answer. +1 to you, Lekensteyn, esp. for getting that hard-to-get badge off of this question ;)
    – Thomas Ward
    Mar 13, 2011 at 18:13
  • Thanks for waiting that long for accepting my question :D I got a Gold Populist badge and a bronze Nice Answer for this answer :) I wonder how this question got that popular, 345 views in a day!
    – Lekensteyn
    Mar 13, 2011 at 21:10
  • I still love using this test: [ -w /etc/shadow ]. If that's true, you might as well be root. ;)
    – Kees Cook
    Mar 14, 2011 at 22:44
  • 3
    I've seen shorter versions, [ -w / ]. The idea remains the same. Note: in certain chroots, [ -w /etc/shadow ] will fail because /etc/shadow is non-existent, therefore the approach with / is preferred. A way better would checking the actual need for root permissions. If the script needs to write to /etc/someconfig, just check if that file is writable OR the file does not exist and /etc is writable.
    – Lekensteyn
    Mar 14, 2011 at 22:47
40

As @Lekensteyn said you should use effective user ID. You don't need to call id -u in bash:

#!/bin/bash

if [[ $EUID -ne 0 ]]; then
   echo "You must be root to do this." 1>&2
   exit 100
fi

@geirha's suggestion from the comments uses arithmetic evaluation:

#!/bin/bash

if (( EUID != 0 )); then
   echo "You must be root to do this." 1>&2
   exit 100
fi
7
  • 9
    In general one should use ((..)) for testing numbers, and [[..]] for testing strings and files, so I'd do if (( EUID != 0 )); then instead, or just if ((EUID)); then
    – geirha
    Mar 13, 2011 at 12:41
  • @geirha: I've added your suggestion.
    – jfs
    Mar 13, 2011 at 13:11
  • 2
    EUID should become $EUID. Instead of using (( $EUID != 0 )), use [ $EUID != 0 ]. It will work with dash too.
    – Lekensteyn
    Mar 13, 2011 at 13:23
  • 2
    @Lekensteyn: EUID works just fine. The question is tagged bash not dash. The command env -i sh -c '[ $EUID != 0 ]' fails, but env -i bash -c '(( EUID != 0 ))' works. btw, dash doesn't work for some non-ascii characters on Ubuntu stackoverflow.com/questions/5160125/… It is 2011 and there are people who use other languages.
    – jfs
    Mar 13, 2011 at 13:39
  • After looking back on this while being horribly bored, and testing, I am going to use this method as listed here with the $EUID stuff from this point forward. I have changed the accepted answer as a result.
    – Thomas Ward
    Aug 3, 2011 at 15:15
22

You can accomplish this by using the whoami command, which returns the current user:

#!/bin/bash

if [ `whoami` != 'root' ]
  then
    echo "You must be root to do this."
    exit
fi

...

Running the above will print You must be root to do this. if the current user is not root.


Note: an alternative in some cases is to simply check the $USER variable:

if [ $USER != 'root' ]
9
  • 4
    @George Edison: I recommend against using $USER, especially in this way. $USER is set by the login shell, it does not necessary propagate to the program (env -i sh -c 'echo $USER'). In that way, $USER is empty and an syntax error occurs.
    – Lekensteyn
    Mar 13, 2011 at 9:26
  • 2
    @Lekensteyn Not only is $USER set by the shell, it is also something that is easy to spoof. Whoami will return the actual user. Mar 13, 2011 at 11:48
  • 2
    @PauldeVrieze What's the point of fooling that check?
    – htorque
    Mar 13, 2011 at 14:01
  • 2
    id -u is a far superior solution. I believe this answer is potentially misleading and should not have been accepted. Mar 13, 2011 at 16:05
  • 2
    @andrewsomething: $USER is interpreted by your shell, your example should be sudo sh -c 'echo $USER' in order to be meaningful. @George: it makes the wrong assumption that whoami will always return root for UID 0. Mar 13, 2011 at 20:26
13

Taking efficiency into consideration, you may test, first, the EUID environment variable and then, if it doesn't exist, call the standard id command:

if ((${EUID:-0} || "$(id -u)")); then
  echo You are not root.
else
  echo Hello, root.
fi

This way, because of the OR shortcut, you avoid calling a system command, prioritizing the query of an in-memory variable.

Code reuse:

function amIRoot() {
  ! ((${EUID:-0} || "$(id -u)"))
}
2
  • 1
    I'm afraid you haven't benchmarked it, well I have and this takes the very same time as id -u. See the bench script along with results below it here: pastebin.com/srC3LWQy Oct 16, 2019 at 23:40
  • 3
    ((${EUID:-0} || "$(id -u)")) always runs id -u, just as ((1 || $(echo hi >&2; echo 1))) and ((0 || $(echo hi >&2; echo 1))) both print hi. Outside shell arithmetic, && and || are control operators; in a || "$(b)", b only runs if "$(b)" runs. Most expansions, including command substitution, are governed by control operators' short-circuiting semantics. Shell arithmetic has operators that happen to be spelled && and ||, too--which also short-circuit in that ((1 || 0/0)) is not an error--but shell arithmetic occurs after nested command substitutions are expanded. Oct 24, 2019 at 18:02
10
#!/bin/bash
[[ $(id -u) != 0 ]] 
echo $?
1
  • 1
    Numeric comparison is better done with -ne (counter-intuitive: text operands are for numeric comparison)
    – Gonen
    Aug 28, 2022 at 20:53
3
#!/bin/bash
if [ "$(id -u)" == "0" ]
then
    echo "I am root."
else
    echo "I am not root."
fi
2

This snippet would:

  • Check on different sessions
  • suggest to use sudo !!
  • and return an error
if [ "$(whoami &2>/dev/null)" != "root" ] && [ "$(id -un &2>/dev/null)" != "root" ]
      then
      echo "You must be root to run this script!"
      echo "use 'sudo !!'"
      exit 1
fi
0
2

This answer is just to save an idea with may be helpful for some of you. If you need script which is run from desktop GUI and requires root privileges try this way:

#!/bin/bash
if ! [ $(id -u) = 0 ]; then
   gksudo -w $0 $@
   exit
fi

#here go superuser commands, e.g. (switch intel cpu into powersave mode):
echo 1 > /sys/devices/system/cpu/intel_pstate/no_turbo
cpupower frequency-set -g powersave

This way you will get nice dialog window asking you for root user password. Just like with command-line sudo.

The gksudo may not be available in your system then install it with sudo apt-get install gksu.

2

One simple way to make the script only runnable by root is to start the script with the line:
#!/bin/su root

2
  • 3
    Don't do this. It attempts to log in directly as root, whereas sudo may be required on many systems because the former is forbidden. Furthermore, the shebang is intended to ensure your script runs in the one for which it was designed, whereas your method will cause the script to run in root's default shell, which cannot be predicted if the script is run by anyone other than the author. Therefore, using the shebang to elevate privileges of a script will severely break its portability and result in errors on many systems. (su: Authentication failure)
    – StarCrashr
    Sep 20, 2018 at 1:59
  • 1
    Don't do this. Some joker might create a second user named root, or make a user named root that isn't root, thereby fooling your program into thinking it's root. See askubuntu.com/a/836621/1070384. Aug 18, 2020 at 22:21
1

This code works under both Bash and stock Bourne sh (tested under FreeBSD) that does not define EUID. If EUID exists its value is returned, else the 'id' command is run. It is a tad shorter than the "or" example above, as it uses a shell built-in ":-".

Root in sh:

# echo $EUID

# euid=${EUID:-`id -u`}
# echo $euid
0

In bash:
[chaapala@tenfwd2 ese]$ euid=${EUID:-`id -u`}
[chaapala@tenfwd2 ese]$ echo $euid
10260
2
  • can you use the more modern euid=${EUID:-$(id -u)} Dec 28, 2021 at 19:09
  • Yes, just as you have it there. Feb 5, 2022 at 22:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .