13

I've got a script I want to require be run with su privileges, but the interesting scripted command that will fail comes very late in the script, so I'd like a clean test up front to determine if the scrip will fail without SU capabilities.

What is a good way to do this for bash, sh, and/or csh?

Thom Wiggers
  • 6,938
  • 1
  • 39
  • 65
F. Randall Farmer
  • 627
  • 1
  • 6
  • 13

2 Answers2

16

bash/sh:

#!/usr/bin/env bash
# (Use #!/bin/sh for sh)
if [ `id -u` = 0 ] ; then
        echo "I AM ROOT, HEAR ME ROAR"
fi

csh:

#!/bin/csh
if ( `id -u` == "0" ) then
        echo "I AM ROOT, HEAR ME ROAR"
endif
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
  • 3
    This code will not work in a POSIX shell (`/bin/sh`). The `[[` command and `EUID` variable are specific to bash -- they're not defined in the POSIX specification. – Richard Hansen Jun 18 '11 at 07:55
  • 2
    Also #!/bin/bash is almost always wrong. If you must use bash (which is really not preferred) use /usr/bin/env bash – Good Person May 25 '13 at 15:31
  • 2
    It seems like bash **is** preferred by people who specifically mention bash in their questions. – jwg Mar 12 '14 at 16:11
12

You might add something like that at the beginning of your script:

#!/bin/sh

ROOTUID="0"

if [ "$(id -u)" -ne "$ROOTUID" ] ; then
    echo "This script must be executed with root privileges."
    exit 1
fi
mhoareau
  • 631
  • 5
  • 6