17

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?

34

This is very easy to accomplish:

#!/bin/sh
[ "$(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" "$@"
  • Sorry, I made an error in the explanation so it might have been misinterpreted. Here is a more clear explanation. Thanks for the help! – Redson 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 – Redson 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 – Redson 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
7

You can check the UID as well:

 if [ $(id -u) != 0 ]; then
     echo "You're not root"
     # elevate script privileges
 fi
5

You can call the script itself and check:

#! /bin/bash

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

...
0

At the point where you want to login, simply add following command

sudo su

This is working perfectly with my code

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.