What's the best way to run sudo from a bash script without being able to run the script as privileged?
I think the best way is to prompt the user for the password, and apply sudo
when its needed within the script. For example, below is from build-git.sh
and build-ssh.sh
. The scripts only use the password with sudo
during the make install
step. (The scripts are used on old OSes, like CentOS 5, which do not offer modern tools).
echo
echo "If you enter a sudo password, then it will be used for installation."
echo "If you don't enter a password, then ensure INSTALL_PREFIX is writable."
echo "To avoid sudo and the password, just press ENTER and they won't be used."
read -s -p "Please enter password for sudo: " SUDO_PASSWWORD
echo
...
# Configure and make without privileges
...
MAKE_FLAGS=(install)
if [[ ! (-z "$SUDO_PASSWWORD") ]]; then
echo "$SUDO_PASSWWORD" | sudo -S "$MAKE" "${MAKE_FLAGS[@]}"
else
"$MAKE" "${MAKE_FLAGS[@]}"
fi
Its probably worth mentioning that I needed to (1) configure and build without privileges, and (2) install with privileges. Making the password optional like in the script served my needs, so its was deemed "best" because it met my requirements and worked with the least amount of effort. Your "best" may vary depending on your requirements.
If you do use the echo
method, then consider disabling or clearing Bash history to avoid logging the password. You can even temporarily disable history if you want to get fancy. The machines I run the scripts on have their history disabled, so its not a concern for me.