When recording using sudo echo x shell script> Permission denied throwing error

1. Scene

And in a non-root user with sudo privileges, use the shell script (separate manual execution command does not throw wrong, is successful): flip a wrong

#!/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. Error

[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. Analyze

In the shell script, bash refused to do so, saying that the authority is not enough.

This is because the redirection symbol ">" is also the bash. sudo just let the echo command has root privileges, but did not let the ">" command also have root privileges, so bash would think that this command does not write access to information.

4. Solution

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

By duct and tee command, which information can be read from the standard input and standard output or write a file,
are used as follows:

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

tee command is useful, it received information from the pipeline, while the output to the screen while writing to the file.

Guess you like

Origin blog.51cto.com/14309075/2414028