Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

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

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?

share|improve this question

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.)

share|improve this answer

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
share|improve this answer

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
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.