没有BASH -C的Sudo Echo的其他方法
我必须在脚本my.sh
中以sudo
在脚本中运行echo
,因为许可。 我不想用sudo my.sh
执行脚本。 我不想使用bash -c“ ...”
,因为逃脱了。
还有其他解决方案吗?
我的
#!/usr/bin/bash
>/file.tmp \
echo '
a="S T"
z=\a\b\c\
'
I must run the echo
in the script my.sh
with sudo
because permission.
I do not want to execute the script with sudo my.sh
.
I do not want to use bash -c "..."
because escaping.
Are there no other solutions?
my.sh
#!/usr/bin/bash
>/file.tmp \
echo '
a="S T"
z=\a\b\c\
'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在这里遇到的问题是,输出重定向
>/file.tmp
必须在提升特权时发生。这意味着您要么必须像sudo my.sh
一样启动脚本,要么以赋予其提升特权的方式执行重定向。这还不足以运行sudo echo
,因为只有echo
具有提高的特权,但是输出重定向将作为您的非root用户运行,因为它是一个shell buildin indentin noundin interiin interion interion inter不是外部命令。有一个称为
TEE
的标准工具可以帮助您解决这个问题。该方法通常在运行curl
以获取需要添加为root的数据时通常使用,例如安装debian apt存储库配置和签名键。因此,您可以看到我与我自己的用户启动了
whoami
,但是由于tee
,该文件最终被编写,因为tee
,它取代了您的原始示例的输出重定向,以sudo tee
启动。The problem you are encountering here is that the output redirection
>/file.tmp
has to happen with elevated privileges. This means that you either have to launch the script as it is withsudo my.sh
, or perform the redirection in a way that gives it elevated privileges. It is not enough to runsudo echo
because onlyecho
would have elevated privileges, but the output redirection would run as your non-root user because it is a shell builtin feature, not an external command.There is a standard tool called
tee
that can help with this. This method is commonly used when runningcurl
to fetch data that needs to be fed to root, such as installing debian apt repository configurations and signing keys.So you can see that I launched
whoami
with my own user, but the file ended up being written with root permissions becausetee
, which replaces the output redirection from your original example, was launched assudo tee
.