rocky-tools icon indicating copy to clipboard operation
rocky-tools copied to clipboard

Run as sudo when needed

Open aminvakil opened this issue 3 years ago • 0 comments

mirrorsync.sh just returns permission denied when running as non-root user trying to write to a directory not owned by itself. I'm not saying to always check for sudo and run it as root as this may lead to unexpected issues for those who do not want to, but it can either ask or just tries to run with sudo when it cannot write to directory.

Something like this will do:

command_exists() {
        command -v "$@" > /dev/null 2>&1
}
user="$(id -un 2>/dev/null || true)"
do_change() {
        user="$(id -un 2>/dev/null || true)"
        sh_c='sh -c'
        if [ "$user" != 'root' ]; then
                if command_exists sudo; then
                        sh_c='sudo -E sh -c'
                elif command_exists su; then
                                sh_c='su -c'
                else
                        cat >&2 <<-'EOF'
                        Error: this installer needs the ability to run commands as root.
                        We are unable to find either "sudo" or "su" available to make this happen.
                        EOF
                        exit 1
                fi
        fi

then run commands with: $sh_c "whatever command"

aminvakil avatar Jun 26 '21 06:06 aminvakil