I have a shell script that contains the following lines:

echo switch to `who am i`

Once the 2nd line is executed, the shell prompts me to enter the root password. After I provide the correct password and login as admin the last line is not getting executed.

What could be the reason for this issue?


su starts a new shell (or runs some other command). It doesn't magically switch the UID of the current shell. If you type exit after entering your password, you'll see that your script continues with the echo statement (but as the original user, not as root).

You can put the part of the script that should be executed as root into a separate script, and execute that with su. (Or some use variation of that trick.)


As far as the shell is concerned, su is a command like any other. When you run su with no argument, it prompt for the root password, then invokes an interactive shell, as usual. Once this interactive shell exits, the script proceeds to the next command.

To pass commands to su without too many quoting headaches, the easy way is to pass a script on its standard input using a here document. Use a literal heredoc (where the end-of-input marker is quoted) to avoid quoting headaches. Note that shell variables of the parent script are not available to the script that is executed as root: only environment variables (exported) are available. Example:

su <<'EOF'
adduser "$ADD_USER" "$ADD_TO_GROUP"
# more commands executed as the original user

Running su starts a new command (the shell by default).

To make this work, try something like this:

if [ `id -u` = 0 ]; then
    # Do our real work as root
    su -c $0

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.