2

The standard-solution for bash, see:

https://askubuntu.com/questions/15853/how-can-a-script-check-if-its-being-run-as-root

which is:

#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi

does not work in dash, which is slowly becoming the standard-shell under Linux. How can the above be ported to dash?

Community
  • 1
  • 1
Robby75
  • 3,285
  • 6
  • 33
  • 52
  • 2
    Use `[ $(id -u) -ne 0 ]` – Martin Tournoij Aug 13 '14 at 08:05
  • If anything, it's *less* standard with several large distributions switching to `dash` as the system shell. (As far as I know, usage of `bash` as the default *login* shell has remained fairly constant over the last 15-20 years.) – chepner Aug 13 '14 at 12:52

3 Answers3

8

Use id:

if [ "$(id -u)" -eq 0 ]; then
    echo "I am root!"
fi

Or

#!/bin/sh
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root" 
    exit 1
fi
konsolebox
  • 72,135
  • 12
  • 99
  • 105
1

What I usually do is check for the capabilities I actually require, so that the script will also work correctly for a user who likes to run via an alternate privileged account (*BSD used to have toor for superuser with csh, which of course nobody in their right mind would want these days, but anyway).

test -w /usr/share/bin ||
{ echo "$0: /usr/share/bin not writable -- aborting" >&2; exit 1 }
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

Use the "id -u" command to get your current effective user id:

#!/bin/dash
MYUID=`id -u`
if [ "$MYUID" -eq 0 ]
then
    echo "You are root"
else
    echo "You are the non-root user with uid $MYUID"
fi
Roland Seuhs
  • 1,878
  • 4
  • 27
  • 51