简体   繁体   中英

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM