天天看點

記錄在shell腳本中使用sudo echo x > 時,抛Permission denied錯誤

1.場景

在一個非root且帶有sudo權限的使用者,使用shell腳本(單獨手工執行指令不會抛錯,是成功的):會抛錯

點選(此處)折疊或打開

#!/bin/bash -x

DNS_SERVER=10.xx.xx.xx;

echo "Add DNS Server";

sudo chattr -i /etc/resolv.conf;

sudo echo "nameserver $DNS_SERVER" > /etc/resolv.conf;

sudo chattr +i /etc/resolv.conf

2.錯誤 

[hadoop@emr-header-1 WNE-2280FFD89A744E81]$ ./init-emr-env.sh

+ DNS_SERVER=10.xx.xx.xx

+ echo 'Add DNS Server'

Add DNS Server

+ sudo chattr -i /etc/resolv.conf

+ sudo echo 'nameserver 10.xxx.xx.xx'

./init-emr-env.sh: line 7: /etc/resolv.conf: Permission denied

+ sudo chattr +i /etc/resolv.conf

+ echo 'remove hive2.0'

 3.分析

在shell腳本中,bash 拒絕這麼做,說是權限不夠.

這是因為重定向符号 “>” 也是 bash 的指令。sudo 隻是讓 echo 指令具有了 root 權限,但是沒有讓 “>” 指令也具有root 權限,是以 bash 會認為這個指令沒有寫入資訊的權限。

4.解決方法

echo "nameserver $DNS_SERVER" | sudo tee /etc/resolv.conf;

利用管道和 tee 指令,該指令可以從标準輸入中讀入資訊并将其寫入标準輸出或檔案中,

具體用法如下:

echo a |sudo tee 1.txt

echo a |sudo tee -a 1.txt   // -a 是追加的意思,等同于 >>

tee 指令很好用,它從管道接受資訊,一邊向螢幕輸出,一邊向檔案寫入。