bash 文件中的 sudo bash 和 sudo 命令有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41156430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:31:59  来源:igfitidea点击:

What is the difference of sudo bash and sudo command in bash file?

bash

提问by mora

I would like to append some commands to ${HOME}/.bashrc file.

我想将一些命令附加到 ${HOME}/.bashrc 文件中。

I made a script to do it.

我做了一个脚本来做到这一点。

# file name : setup_bash
bashrc_path="${HOME}/.bashrc"
comment="test"
sudo echo "${comment}" >> "${bashrc_path}"

and run it by

并运行它

bash setup_bash

And it results in an error.

它会导致错误。

setup_bash: line 19: /home/user/.bashrc: Permission denied

line 19 is at (sudo echo ...).

第 19 行在 (sudo echo ...)。

Next I tried the following code,

接下来我尝试了以下代码,

sudo bash setup_bash

It results in success.

结果是成功。

What is the difference of them? Please teach me it.

它们的区别是什么?请教我。

回答by larsks

Shell i/o redirection happens beforea command executes. That is, when you run...

Shell i/o 重定向发生命令执行之前。也就是说,当你跑...

sudo echo "some text" >> /some/path

...the shell opens /some/pathfor input before it ever runs the echocommand. The implication of this is that the i/o redirection is notgoing to be affected by the sudocommand (because the redirection happens before sudoeven runs). On the other hand, when you run...

...外壳/some/path在运行echo命令之前打开以供输入。这意味着 i/o 重定向不会受到sudo命令的影响(因为重定向发生sudo运行之前)。另一方面,当你跑...

sudo bash setup_bash

...you are running the entire scriptas the root user, which means that when it comes time to perform the i/o redirection the script is already running as rootand so the redirection will succeed.

...您正在以 root 用户身份运行整个脚本,这意味着当需要执行 i/o 重定向时,脚本已经在运行root,因此重定向将成功。

回答by heemayl

The problem is that in

问题是在

sudo echo "${comment}" >> "${bashrc_path}"

the shell (STDOUT) redirection (write -- append) operation >> "${bashrc_path}"is done first by the shell, as the user invoking user, this is done even before the main command is executed. And presumably the invoking user has no permission to open the file for writing, hence the permission denied error message from shell; this is irrespective of the command sudo echo ...because that command has not been started executing even by then.

shell (STDOUT) 重定向(写入 -- 追加)操作>> "${bashrc_path}"首先由 shell 完成,作为调用用户的用户,这甚至在执行主命令之前就已完成。并且大概调用用户没有打开文件进行写入的权限,因此来自shell的权限被拒绝错误消息;这与命令sudo echo ...无关,因为即使到那时该命令还没有开始执行。

Now when you used sudoat invocation time you are impersonating root(default) so the redirection -- write (append) operation would succeeed, (and as you might have guessed you don't even need the sudoin front of echonow).

现在,当您sudo在调用时使用时,您正在模拟root(默认),因此重定向 - 写入(追加)操作将成功,(并且您可能已经猜到,您现在甚至不需要sudo前面的echo)。