Skip to content

Instantly share code, notes, and snippets.

@NathanaelGandhi
Last active June 8, 2023 23:03
Show Gist options
  • Save NathanaelGandhi/96f735c0906c15b69a2de6b4d6561d76 to your computer and use it in GitHub Desktop.
Save NathanaelGandhi/96f735c0906c15b69a2de6b4d6561d76 to your computer and use it in GitHub Desktop.
bash function to ensure that the script is run with root privileges
#!/bin/bash -eu
# author: Nathanael Gandhi
# github.com/NathanaelGandhi
# If the user is not root, it performs the following actions:
# 1. It assigns the absolute path of the currently running script to the variable exe_name using the readlink -f command. This ensures that exe_name contains the full path of the script even if it was executed using a relative path.
# 2. It then uses sudo to execute the script again as root, passing the same script path ($exe_name) and any command-line arguments ($@) to it.
# 3. Finally, it exits the current instance of the script with the same exit code ($?) as the root-executed script.
# In summary, this code snippet is designed to ensure that the script is run with root privileges. If it's not being run as root, it will re-execute itself using sudo to gain the necessary privileges.
################################################################################
# force root-execution of the script #
################################################################################
function forceRootExecution()
{
if [[ ! "$USER" == "root" ]] ; then
echo " • Forcing root execution"
exe_name="$(readlink -f -- "$0")"
sudo "$exe_name" "$@"
exit $?
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment