While executing commands that needs root permission, I rely on sudo. Sudo provides me a very convenient way to execute root privilege commands from my user account provided with my user account password.
Sudo and su are not the same, check out more from here.
When comes to scripting, I couldn’t use sudo directly. For examples I make up a script modifying /etc/resolv.conf with my DNS settings. In order to modify /etc/resolv.conf, I need root permission. But I couldn’t execute commands directly with sudo in the script.
Below showing the script that DOES NOT work.
#!/bin/bash # the lines below doesn't work!!! sudo echo "nameserver 18.104.22.168" > /etc/resolv.conf sudo echo "nameserver 22.214.171.124" >> /etc/resolv.conf cat /etc/resolv.conf
I can write all our commands that need root permission in the script, then externally execute the script with sudo. Let say my script is set_dns.sh.
The line above works! But what if I want to run it as normal user and it prompts me for sudo password? I figure out a way, I can do that with the script below.
#!/bin/bash if [ "$1" == 'done' ] then #the commands needs root permission list as below echo "nameserver 126.96.36.199" > /etc/resolv.conf echo "nameserver 188.8.131.52" >> /etc/resolv.conf cat /etc/resolv.conf else sudo $0 done fi
I make it as a template, I just have to replace the portion between ‘then’ and ‘else’.