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

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

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

我刚刚收到回复:

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

我怎样才能让它工作呢?


当前回答

写一个脚本怎么样?

Filename: myscript

#!/bin/sh

/bin/ls -lah /root > /root/test.out

# end script

然后使用sudo运行脚本:

sudo ./myscript

其他回答

sudo at now  
at> echo test > /tmp/test.out  
at> <EOT>  
job 1 at Thu Sep 21 10:49:00 2017  

这个主题还有另一个变体:

sudo bash <<EOF
ls -hal /root/ > /root/test.out
EOF

或者当然:

echo 'ls -hal /root/ > /root/test.out' | sudo bash

它们有一个(微小的)优势,即您不需要记住sudo或sh/bash的任何参数

问题是命令在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';

我自己发现的一个把戏

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

我对这个问题的看法是:

如果您需要写入/替换文件:

echo "some text" | sudo tee /path/to/file

如果你需要追加到文件:

echo "some text" | sudo tee -a /path/to/file