简体   繁体   English

sudo cat << EOF > 文件不起作用,sudo su 起作用

[英]sudo cat << EOF > File doesn't work, sudo su does

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.然后我做了sudo su并尝试了完全相同的事情,除了cat之前的sudo ,它没有任何问题。 What am I missing in the above ?我在上面缺少什么?

Output redirection (eg, >) is performed by bash, not by cat, while running with your UID.在使用您的 UID 运行时,输出重定向(例如,>)由 bash 执行,而不是由 cat 执行。 To run with root's UID use sudo:要使用 root 的 UID 运行,请使用 sudo:

sudo bash -c 'cat << EOF > /etc/yum.repos.d/some-name.repo
line1
line2
line3
EOF'

Another option is tee.另一种选择是三通。

cat << EOF | sudo tee -a /etc/yum.repos.d/some-name.repo
...
EOF

As a variation to @Yuriy Nazarov's answer, only the piped output needs to be elevated thru sudo .作为@Yuriy Nazarov 答案的一个变体,只有管道输出需要通过sudo提升。 The piped input can stay un-elevated:管道输入可以保持未提升:

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发送。

As others have pointed out the shell redirection is done by the current shell not by cat.正如其他人所指出的,shell 重定向是由当前 shell 完成的,而不是由 cat 完成的。 sudo only changes the permission of the program that is executed not of the shell doing the redirect. sudo 只更改执行的程序的权限,而不是执行重定向的 shell。 My solution to this is to avoid the redirect:我对此的解决方案是避免重定向:

sudo dd of=/etc/yum.repos.d/some-name.repo << EOF

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 上测试的

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

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