Bash – Prompt for Sudo Password and Programmatically Elevate Privilege in Bash Script

bashsudo

I'm currently working on a bash script that installs and sets up various programs on a stock Linux system (currently, Ubuntu). Because it installs programs and copies a number of files to various folders that require elevated privileges, I've already done the standard "I need elevated privileges"-and-exit.

However, I would like, if possible, to be able to prompt the user for their sudo password and elevate the script's privileges automatically if the user doesn't run the script command with sudo (such as launching it from the GUI file manager), without the user having to restart the script.

As this is designed to run on stock Linux installs, any option that modifies the system won't work for my purposes. All options need to be contained to the script itself.

Is this possible within Bash? If so, what's the best (secure, yet concise) way to do this?

Best Answer

I run sudo directly from the script:

if [ $EUID != 0 ]; then
    sudo "$0" "$@"
    exit $?
fi
Related Question