Linux – Bash script normal user to Root

bashlinuxroot

I have some question. I'm trying to create some bash script to automatically some task. I need to do the first step of the task as normal user, and su – to be root to finish the task.

I've been wondering if there is a way to do that? Until now i'm only been able to start the bash as normal user, complete the first step, ask for su – password, but after it connect as root, the script stop.

Is it possible to proceed with the bash after been logged as root?

Thank you in advance.

ps : If I'm not precise, or if you need some information, feel free to ask, I'll do my possible to correct those mistake.

Best Answer

Have you tried using sudo somecommand instead of trying to switch users? Your user will need to be in the 'wheel' user group (depending on your system) to do that.

su changes the environment (user variables etc.) so, though I haven't tested this, you probably can't do it in a shell script.

Example:
Your shell script was

#Do these commands as a normal user
echo "Hello World"
cat ./somefile

#Do these commands as root
su -
echo "Hello again"
cat /etc/somesystemfile

try changing it to

#Do these commands as a normal user
echo "Hello World"
cat ./somefile

#Do these commands as root
sudo echo "Hello again"
sudo cat /etc/somesystemfile