我如何使用sudo将输出重定向到我没有写权限的位置?

问题描述 投票:874回答:15

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

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

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

我刚刚收到回复:

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

我该如何使用它?

linux permissions sudo io-redirection permission-denied
15个回答
1223
投票
is]的重定向。

有多种解决方案:

    使用sudo运行shell并使用-c选项向其发出命令:
  • sudo sh -c 'ls -hal /root/ > /root/test.out'

    使用命令创建脚本并使用sudo运行该脚本:
  • #!/bin/sh ls -hal /root/ > /root/test.out

    运行sudo ls.sh。如果您不想创建临时文件,请参见Steve Bennett的answer

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

  • [nobody@so]$ sudo -s [root@so]# ls -hal /root/ > /root/test.out [root@so]# ^D [nobody@so]$

    使用sudo tee(如果使用-c选项时必须逃避很多):
  • sudo ls -hal /root/ | sudo tee /root/test.out > /dev/null

    需要重定向到/dev/null,才能停止tee输出到屏幕。要

    append
    而不是覆盖输出文件(>>),使用tee -atee --append(最后一个特定于GNU coreutils)。
  • 感谢第二,第三和第四种解决方案的JdAdam J. ForsterJohnathan


4
投票

4
投票

3
投票

2
投票

1
投票

1
投票

105
投票

81
投票

45
投票
command

23
投票

18
投票
澄清为什么最好使用tee选项

17
投票

11
投票

5
投票
© www.soinside.com 2019 - 2024. All rights reserved.