Take the 2-minute tour ×
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.

I have a shell script that contains the following lines:

CURRENT_USER=${USER}
echo $CURRENT_USER
su
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
add comment

3 Answers

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:

ADD_USER=john
ADD_TO_GROUP=fiddlers
export ADD_USER ADD_TO_GROUP
su <<'EOF'
adduser "$ADD_USER" "$ADD_TO_GROUP"
EOF
# more commands executed as the original user
share|improve this answer
add comment

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

To make this work, try something like this:

#!/bin/bash
if [ `id -u` = 0 ]; then
    # Do our real work as root
else
    su -c $0
fi
share|improve this answer
add comment

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
add comment

Your Answer

 
discard

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.