Running command under root user in bash script

Default featured post

Sometimes there are cases that required to run certain commands under root user in bash scripts. However, for switching the root, user must key in the root password. In such conditions the best approach is to utilize sudo command with -S parameter to be able to run a process under root user. Check out the example,

$ echo "rootPassword" | sudo -S mkdir /root/test123

You should keep in mind still there is a difference between running a command with sudo and with root user. There was a case that I have encountered and I was got mixed results with running the command under root and with sudo. After little bit searching realized, the problem has come from environmental variables and fortunately sudo command has a switch to run the command under root environment variables,

$ echo "rootPassword" | sudo -S -i mkdir /root/test123

Another difficulty that system admins might face is how to run more than one command through sudo command, with little bit of searching I found the following trick works fine,

$ echo "rootPassword" | sudo -S -i -- sh -c 'rm -rvf /root/test123; whoami; mkdir /root/tpx'