Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if running as root in a bash script

Tags:

bash

shell

root

I'm writing a script that requires root level permissions, and I want to make it so that if the script is not run as root, it simply echoes "Please run as root." and exits.

Here's some pseudocode for what I'm looking for:

if (whoami != root)   then echo "Please run as root"    else (do stuff) fi  exit 

How could I best (cleanly and securely) accomplish this? Thanks!

Ah, just to clarify: the (do stuff) part would involve running commands that in-and-of themselves require root. So running it as a normal user would just come up with an error. This is just meant to cleanly run a script that requires root commands, without using sudo inside the script, I'm just looking for some syntactic sugar.

like image 364
Nathan Avatar asked Aug 13 '13 17:08

Nathan


People also ask

How do I know if a process is running as root?

From man ps : To see every process running as root (real & effective ID) in user format: ps -U root -u root u . Or you can use a task manager that shows a 'user' column (top, htop, ksysguard, etc.).

How do I run as root in bash?

To give root privileges to a user while executing a shell script, we can use the sudo bash command with the shebang. This will run the shell script as a root user. Example: #!/usr/bin/sudo bash ....


1 Answers

The $EUID environment variable holds the current user's UID. Root's UID is 0. Use something like this in your script:

if [ "$EUID" -ne 0 ]   then echo "Please run as root"   exit fi 

Note: If you get 2: [: Illegal number: check if you have #!/bin/sh at the top and change it to #!/bin/bash.

like image 94
ptierno Avatar answered Sep 20 '22 15:09

ptierno