Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The problem I am getting is, when I enter the command,

su - root

at the beginning of my shell script file, it prompts the user to enter the password and then does NOT continue with the rest of the shell script. I then have to manually locate and run the shell script via terminal. I want the script to make sure that the user logs in as root and then continue with the rest of the shell script.

In other words, I want to run the script as any user but as soon as the script begins to execute, the user must change to root and then continue on with the rest of the script as root until it is done. Can this be done?

share|improve this question
up vote 25 down vote accepted

This is very easy to accomplish:

[ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"

When the current user isn't root, re-exec the script through sudo.

Note that I am using sudo here instead of su. This is because it allows you to preserve arguments. If you use su, your command would have to be su -c "$0 $@" which would mangle your arguments if they have spaces or special shell characters.

If your shell is bash, you can avoid the external call to whoami:

(( EUID != 0 )) && exec sudo -- "$0" "$@"
share|improve this answer
Sorry, I made an error in the explanation so it might have been misinterpreted. Here is a more clear explanation. Thanks for the help! – Alias May 29 '14 at 17:28
@user68857 Your question was clear. This answer does exactly what you want. – Patrick May 29 '14 at 17:30
i keep getting this error: sudo: must be setuid root – Alias May 29 '14 at 17:32
i want to run the script as a regular user via terminal but the script should then switch the user to root until the end of the script – Alias May 29 '14 at 17:37
@Nosscire if you're getting sudo: must be setuid root, then something happened to your sudo. To fix it: chmod u+s $(which sudo). And yes, I'm well aware of what you're trying to do, I do the same thing all the time in my scripts. – Patrick May 29 '14 at 17:42

You can check the UID as well:

 if [ $(id -u) != 0 ]; then
     echo "You're not root"
     # elevate script privileges
share|improve this answer

You can call the script itself and check:

#! /bin/bash

if [ "root" != "$USER" ]; then
  su -c "$0" root

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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