This answer is similar to terdon's answer. As I would also suggest running the main script with sudo so you can run the commands without asking the user for any password.
However, in case you want to run some of the commands not as the root user or a specific system user, but as the actual user who ran the command with sudo, you can check for the $SUDO_USER variable to figure out the original user.
This is an example script of how you could achieve that:
#!/bin/bash
# ref: https://askubuntu.com/a/30157/8698
if ! [ $(id -u) = 0 ]; then
echo "The script need to be run as root." >&2
exit 1
fi
if [ $SUDO_USER ]; then
real_user=$SUDO_USER
else
real_user=$(whoami)
fi
# Commands that you don't want run with root would be invoked
# with: sudo -u $real_user
# So they will be ran as the user who invoked the sudo command
# Keep in mind, if the user is using a root shell (they're logged in as root),
# then $real_user is actually root
# sudo -u $real_user non-root-command
# Commands that need to be ran with root would be invoked without sudo
# root-command
sudopassword - the script won't be able to run fully if someone is not there to enter it. – Wilf Feb 24 '14 at 23:04sudoerssetup . No big deal. It just needs fixed. – SDsolar Oct 11 '17 at 22:02