Only run part of a bash script as root
by iicapn from LinuxQuestions.org on (#59KVH)
I've tried a few different ways, but can't quite seem to put my finger on it...
I have a bash script, and 1) want to ask the user to enter their password just once. But 2) only want to execute certain parts of the script with elevated privileges.
I know this isn't right, but I'm thinking maybe an approach like this where if I need sudo commands, I nest it into an IF statement.
Code:if [ "$EUID" != 0 ]; then
sudo bash "$0" "$@";
# Reset conf files:
sudo cp /usr/local/etc/httpd/httpd.conf.original /usr/local/etc/httpd/httpd.conf > /dev/null 2>&1
sudo cp /etc/hosts.original /etc/hosts > /dev/null 2>&1
exit "$?";
fi
If this is the right approach, then every time I need sudo commands, I can nest it into an IF statement...
Thank you!


I have a bash script, and 1) want to ask the user to enter their password just once. But 2) only want to execute certain parts of the script with elevated privileges.
I know this isn't right, but I'm thinking maybe an approach like this where if I need sudo commands, I nest it into an IF statement.
Code:if [ "$EUID" != 0 ]; then
sudo bash "$0" "$@";
# Reset conf files:
sudo cp /usr/local/etc/httpd/httpd.conf.original /usr/local/etc/httpd/httpd.conf > /dev/null 2>&1
sudo cp /etc/hosts.original /etc/hosts > /dev/null 2>&1
exit "$?";
fi
If this is the right approach, then every time I need sudo commands, I can nest it into an IF statement...
Thank you!