在shell中使用>
重定向输出提示没有权限怎么办
目标
使用输出重定向符’>‘或’>>'将标准输出重定向到/opt/1.log
解法:
sudo sh -c 'echo "hello world" > /opt/1.log'
或su root
切换到root用户再操作
下文是详细说明
- 尝试执行这个shell脚本:
echo "hello world" > /opt/1.log
会提示没有权限。
sh-4.3$ echo "hello world" > /opt/1.log
sh: /opt/1.log: Permission denied # 没有写入权限
sh-4.3$ whoami
bob # 用户:bob
sh-4.3$ ls -l / | grep opt
drwxr-xr-x 4 root root 4096 Oct 18 16:38 opt
- 第一时间肯定会想到加上sudo:
sudo echo "hello world" > /opt/1.log
sh-4.3$ sudo echo "hello world" > /opt/1.log
sh: /opt/1.log: Permission denied
连密码输入环节都没有
- 经过查询,
>
和>>
根本就不是命令,sudo
也就不会对他们有效果。他们是sh
,bash
等主流外壳可以识别的一个操作符,因此重定向的操作是解释器外壳的行为。因此,如果解释器有了root权限,这个活就可以干了。
sudo sh -c 'echo "hello world" > /opt/1.log'
[sudo] password for bob:
cat /opt/1.log
hello world
sudo sh -c 'echo "hello world" >> /opt/1.log'
hello world
hello world
- 当然也可以用第二种方法切换到root用户再执行带有
>
或>>
的命令