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

问题是,这个人为的例子不起作用:

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

我刚刚收到回复:

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

我怎样才能让它工作呢?


当前回答

每当我要做这样的事情时,我就变成root:

# sudo -s
# ls -hal /root/ > /root/test.out
# exit

这可能不是最好的方法,但确实有效。

其他回答

我自己发现的一个把戏

sudo ls -hal /root/ | sudo dd of=/root/test.out

问题是命令在sudo下运行,而重定向在您的用户下运行。这是由shell完成的,对此您几乎无能为力。

sudo command > /some/file.log
`-----v-----'`-------v-------'
   command       redirection

通常绕过这个的方法是:

Wrap the commands in a script which you call under sudo. If the commands and/or log file changes, you can make the script take these as arguments. For example: sudo log_script command /log/file.txt Call a shell and pass the command line as a parameter with -c This is especially useful for one off compound commands. For example: sudo bash -c "{ command1 arg; command2 arg; } > /log/file.txt" Arrange a pipe/subshell with required rights (i.e. sudo) # Read and append to a file cat ./'file1.txt' | sudo tee -a '/log/file.txt' > '/dev/null'; # Store both stdout and stderr streams in a file { command1 arg; command2 arg; } |& sudo tee -a '/log/file.txt' > '/dev/null';

每当我要做这样的事情时,我就变成root:

# sudo -s
# ls -hal /root/ > /root/test.out
# exit

这可能不是最好的方法,但确实有效。

让sudo运行一个shell,像这样:

sudo sh -c "echo foo > ~root/out"

我会这样做:

sudo su -c 'ls -hal /root/ > /root/test.out'