简体   繁体   English

在 bash 脚本中切换到 root 用户

[英]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.我目前以管理员身份登录,我想编辑需要root访问权限的/etc/hosts文件。

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 sudo -s - 从终端执行时切换到没有密码的 root

su admin - switches back to admin user when run on terminal su admin - 在终端上运行时切换回管理员用户

My /etc/hosts file remains empty after running the script运行脚本后,我的 /etc/hosts 文件保持为空

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.此外,您不能像这样以 root 身份echo某些内容,因为重定向 ( >> ) 是由 shell 执行的。

A possible workaround is using tee :一种可能的解决方法是使用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. tee基本上从标准输入获取数据并将其写入标准输出或文件。 For more information see the commands manual ($ man tee )有关更多信息,请参阅命令手册 ($ man tee )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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