bash sudo cat << EOF > 文件不起作用,sudo su 起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18836853/
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
sudo cat << EOF > File doesn't work, sudo su does
提问by iamauser
I tried the following on the command prompt in bash:
我在 bash 的命令提示符下尝试了以下操作:
sudo cat << EOF > /etc/yum.repos.d/some-name.repo
#Content
#....
#...
EOF
It complained :
它抱怨说:
-bash: /etc/yum.repos.d/some-name.repo: Permission denied
Then I did sudo su
and tried the exact same thing except the sudo
before cat
, and it worked without any problem. What am I missing in the above ?
然后我做了sudo su
并尝试了完全相同的事情,除了sudo
before cat
,它没有任何问题。我在上面缺少什么?
回答by Yuriy Nazarov
Output redirection (e.g., >) is performed by bash, not by cat, while running with your UID. To run with root's UID use sudo:
在使用您的 UID 运行时,输出重定向(例如,>)由 bash 执行,而不是由 cat 执行。要使用 root 的 UID 运行,请使用 sudo:
sudo bash -c 'cat << EOF > /etc/yum.repos.d/some-name.repo
line1
line2
line3
EOF'
回答by Mark
Another option is tee.
另一种选择是三通。
cat << EOF | sudo tee -a /etc/yum.repos.d/some-name.repo
...
EOF
回答by Stephen Quan
As a variation to @Yuriy Nazarov's answer, only the piped output needs to be elevated thru sudo
. The piped input can stay un-elevated:
作为@Yuriy Nazarov 答案的一个变体,只有管道输出需要通过sudo
. 管道输入可以保持未提升:
sudo bash -c 'cat > /etc/yum.repos.d/some-name.repo' << EOF
line1
line2
line3
EOF
This means a much smaller portion of the command needs to be quoted and sent thru to sudo
.
这意味着命令的一小部分需要被引用并通过sudo
.
回答by user2359330
As others have pointed out the shell redirection is done by the current shell not by cat. sudo only changes the permission of the program that is executed not of the shell doing the redirect. My solution to this is to avoid the redirect:
正如其他人所指出的,shell 重定向是由当前 shell 完成的,而不是由 cat 完成的。sudo 只更改执行的程序的权限,而不是执行重定向的 shell。我对此的解决方案是避免重定向:
sudo dd of=/etc/yum.repos.d/some-name.repo << EOF
回答by Alp Altunel
if you are using ' inside the text then you may use:
如果您在文本中使用 ' 那么您可以使用:
$ sudo bash -c "cat > /etc/postfix/mysql-virtual_forwardings.cf << EOF
user = mail_admin
password = password
dbname = mail
query = SELECT destination FROM forwardings WHERE source='%s'
hosts = 127.0.0.1
EOF
"
this is tested on google cloud's virtual server centos 7.0
这是在谷歌云的虚拟服务器 centos 7.0 上测试的