Today I Learned: Auto sudo bash scripts

Brendan Thompson • 7 April 2021

This is an old piece of knowledge that I recently needed to extract from my head. There are many situations where the execution of a script requires sudo to be able to operate correctly, as we are all humans sometimes we forget to sudo scripts. Just because we might forget to sudo does not mean that the exectuion should fail.

The following snippet can be added to any bash script. What it does is checks to see if the executing user is root and if it's not it will grab the entire contents of the script and pass it through a sudo operation.

if [[ $(id -u) -ne 0 ]]; then
    printf -v cmd_str '%q ' "$0" "$@"
    exec sudo su -c "$cmd_str"
fi