Skip to content
Advertisement

Switch to root user within bash script

Im currently logged in as admin and I want to edit the /etc/hosts file which required root access.

I’m not able to make the changes. The script gets executed sucessfully but the changes arent made.

My Script – Runs Sucessfully when executed from terminal

sudo -s
echo "127.0.0.1" >> /etc/hosts
su admin

sudo -s – switches to root without password when executed from terminal

su admin – switches back to admin user when run on terminal

My /etc/hosts file remains empty after running the script

Advertisement

Answer

There is no need to actually switch your user within the script.
Also, you can’t echo something as root like that because the redirect (>>) is executed by the shell.

A possible workaround is using tee:

echo "127.0.0.1" | sudo tee -a /etc/hosts

Further explanation:

tee basically takes the data from the standard input and writes it either to the standard output, or to a file. For more information see the commands manual ($ man tee)

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement