The script presented is a wrapper that writes a separate script in /tmp
and uses the sudo
command to execute that with elevated privileges. The reason to do it that way would be to accommodate the possibility that root cannot access the original file, which might be the case if the file resides on a network file system, if mandatory access controls (e.g. SELinux) prevent it, or perhaps for other reasons.
Is there a better way to do this so the shell won't read the script before it runs?
Of course the shell needs to read the script in order to run it, so I take you to be asking about the creation of an additional script. That is necessary if you want to accommodate the possibility that root cannot access the original script, though the example implementation is dangerously poor. If you aren't worried about that possibility then no, it is not necessary to make a separate script. In that case, one might instead do this:
#!/bin/bash
[[ $EUID -eq 0 ]] || exec sudo /bin/bash -c "${BASH_SOURCE[0]}"
some script here
That checks whether the script is running with effective user ID 0, and if not, uses sudo
to relaunch itself. It does not depend on the original script to be marked executable. Like the example script, this will be subject to authentication and authorization via sudo
, which is the only thing that makes the automatic privilege elevation at all reasonable as far as I am concerned.