Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

linux - 如何使用sudo将输出重定向到我没有写权限的位置?(How do I use sudo to redirect output to a location I don't have permission to write to?)

I've been given sudo access on one of our development RedHat linux boxes, and I seem to find myself quite often needing to redirect output to a location I don't normally have write access to.

(我已经在我们的开发RedHat linux机器上获得了sudo访问权限,而且我似乎经常发现自己需要将输出重定向到我通常没有写访问权限的位置。)

The trouble is, this contrived example doesn't work:

(麻烦的是,这个人为的例子不起作用:)

sudo ls -hal /root/ > /root/test.out

I just receive the response:

(我刚收到回复:)

-bash: /root/test.out: Permission denied

How can I get this to work?

(我该如何工作?)

  ask by Jonathan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your command does not work because the redirection is performed by your shell which does not have the permission to write to /root/test.out .

(您的命令不起作用,因为重定向是由您的外壳执行的,该外壳无权写入/root/test.out 。)

The redirection of the output is not performed by sudo.

(sudo 执行输出的重定向。)

There are multiple solutions:

(有多种解决方案:)

  • Run a shell with sudo and give the command to it by using the -c option:

    (使用sudo运行shell并使用-c选项向其提供命令:)

     sudo sh -c 'ls -hal /root/ > /root/test.out' 
  • Create a script with your commands and run that script with sudo:

    (使用命令创建脚本,然后使用sudo运行该脚本:)

     #!/bin/sh ls -hal /root/ > /root/test.out 

    Run sudo ls.sh .

    (运行sudo ls.sh)

    See Steve Bennett's answer if you don't want to create a temporary file.

    (如果您不想创建临时文件,请参见Steve Bennett的答案 。)

  • Launch a shell with sudo -s then run your commands:

    (使用sudo -s启动shell,然后运行命令:)

     [nobody@so]$ sudo -s [root@so]# ls -hal /root/ > /root/test.out [root@so]# ^D [nobody@so]$ 
  • Use sudo tee (if you have to escape a lot when using the -c option):

    (使用sudo tee (如果使用-c选项时必须转义很多):)

     sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null 

    The redirect to /dev/null is needed to stop tee from outputting to the screen.

    (需要重定向到/dev/null才能阻止tee输出到屏幕。)

    To append instead of overwriting the output file ( >> ), use tee -a or tee --append (the last one is specific to GNU coreutils ).

    (要附加而不是覆盖输出文件( >> ),请使用tee -atee --append (最后一个特定于GNU coreutils )。)

Thanks go to Jd , Adam J. Forster and Johnathan for the second, third and fourth solutions.

(感谢JdAdam J. ForsterJohnathan提供第二,第三和第四种解决方案。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...