What is the error of throwing Permission denied when using sudo echo x & gt; in a shell script
Today, I will talk to you about the error of throwing Permission denied when using sudo echo x > in shell scripts. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
1. Scene
In a non-root user with sudo authority, use the shell script (manual execution of the command alone will not make a mistake, it will be successful): it will throw an error
#! / 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
two。 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. Analysis.
In the shell script, bash refused to do so, saying it was not authorized enough.
This is because the redirection symbol ">" is also a command for bash. Sudo just gives the echo command root permission, but not the ">" command also has root permission, so bash will assume that the command does not have permission to write information.
4. Solution method
Echo "nameserver $DNS_SERVER" | sudo tee / etc/resolv.conf
Using the pipe and tee command, this command can read information from standard input and write it to standard output or file
The specific usage is as follows:
Echo a | sudo tee 1.txt
Echo a | sudo tee-a 1.txt / /-a means append, which is equivalent to > >
The tee command is easy to use, taking information from the pipe, outputting it to the screen and writing to the file.
After reading the above, do you have any further understanding of the error of throwing Permission denied when using sudo echo x > in shell scripts? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.