Skip to content

Instantly share code, notes, and snippets.

@bluPhy
Last active October 5, 2023 16:59
Show Gist options
  • Save bluPhy/67edae660e950490c4de57427d47c8ab to your computer and use it in GitHub Desktop.
Save bluPhy/67edae660e950490c4de57427d47c8ab to your computer and use it in GitHub Desktop.
#!/bin/bash
# Put this at the top of your script
# Detects if script are not running as root, if not will self invoke the script with sudo
# $0 is the script itself (or the command used to call it)...
# $* parameters...
# In both cases using double quote to prevent globbing and word splitting.
# Check if script is being run as root
if [[ $UID -ne 0 ]]; then
# Check if sudo is installed
if command -v sudo &>/dev/null; then
# Re-run script with sudo
exec sudo "$0" "$@"
else
# Print error message and exit
printf "Error: sudo is not installed. Please run this script as root.\n" >&2
exit 1
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment