在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用戶再執行帶有
>
或>>
的命令