Changing to root user inside shell script

Viewed 93362

I have a shell script which needs non-root user account to run certain commands and then change the user to root to run the rest of the script. I am using SUSE11. I have used expect to automate the password prompt. But when I use spawn su - and the command gets executed, the prompt comes back with root and the rest of the script does not execute.

Eg.

< non-root commands>
 spawn su -
<root commands>

But after su - the prompt returns back with user as root. How to execute the remaining of the script.

The sudo -S option does not help as it does not run sudo -S ifconfig command which I need to find the IP address of the machine.

I have already gone through these links but could not find a solution: Change script directory to user's homedir in a shell script

Changing unix user in a shell script

5 Answers

Short version: create a block to enclose all commands to be run as root.

For example, I created a script to run a command from a root subdirectory, the segment goes like this:

sudo su - <<EOF
cd rootSubFolder/subfolder
./commandtoRun
EOF

Also, note that if you are changing to "root" user inside a shell script like below one, few Linux utilities like awk for data extraction or defining even a simple shell variable etc will behave weirdly.

To resolve this simply quote the whole document by using <<'EOF' in place of EOF.

sudo -i <<'EOF'
ls
echo "I am root now"
EOF
Related