109

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?

11 Answers 11

156
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi
  • 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 '10 at 11:59
  • 18
    Also, $UID and $EUID are bashisms. Merely POSIX compliant shells don't have those variables and you need to use id(1) instead. – David Foerster Oct 16 '14 at 9:28
  • 3
    in a bash script, you could use if ((EUID)); then, see @geirha's comment – jfs Oct 17 '14 at 19:38
  • 7
    @Andrew: Variables are substituted before they are passed to sudo. If you run sudo sh -c 'echo $EUID' you will see your expected results. – M. Dudley Nov 19 '15 at 18:09
  • 6
    @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. – Adrian Günter May 9 '17 at 21:40
118

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
  • 5
    You don't need id -u in bash askubuntu.com/questions/30148/… – jfs Mar 13 '11 at 10:27
  • 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 '11 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 '11 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 '11 at 21:10
  • 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 '11 at 22:47
30

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
  • 8
    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 '11 at 12:41
  • @geirha: I've added your suggestion. – jfs Mar 13 '11 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 '11 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 '11 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 '11 at 15:15
19

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' ]
  • I'll take a look at the code, see if it doesn’t make the script fail or something. If it works, I'll accept your answer :) – Thomas Ward Mar 13 '11 at 7:40
  • 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 '11 at 9:26
  • 1
    @Lekensteyn Not only is $USER set by the shell, it is also something that is easy to spoof. Whoami will return the actual user. – Paul de Vrieze Mar 13 '11 at 11:48
  • 2
    @PauldeVrieze What's the point of fooling that check? – htorque Mar 13 '11 at 14:01
  • 1
    @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. – sam hocevar Mar 13 '11 at 20:26
10

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)"))
}
  • 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 – LinuxSecurityFreak Oct 16 at 23:40
  • ((${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. – Eliah Kagan Oct 24 at 18:02
9
#!/bin/bash
[[ $(id -u) != 0 ]] 
echo $?
2

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

  • 1
    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 '18 at 1:59
1
#!/bin/bash
uid=`id -u`
if [ "$uid" == "0" ]
then
    echo 1
else
    echo 0
fi
1

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
1

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.