I have a working bash script, that may run from 0 to 8-9 minutes. It requires
sudo if it finds a problem and needs to change permissions/ownership on a file. I do not want to wait for the
sudo prompt, as this might be a few minutes into the run, so I do
sudo -v at the beginning of the script.
If I expect the script to take long, I often walk over to the cafeteria. So some time ago I included a trap handler, that calls a function, that does
sudo -k to drop my credentials. This way pressing Ctrl+C does not leave someone with access to
sudo while I am not back yet. I do also call that function at the end of the script, in case the script terminates before I am back.
If I already did a
sudo command before calling the script,
sudo -v, it doesn't ask me for my credentials. That is nice.
Depending on where I start I know the script is not going to take long, and I wait for it to finish. If I started it after having just done a
sudo command, every time I end up without
sudo credentials after it finishes.
I did check the return value of
sudo -v. On exit 0, that doesn't tell me if the credentials were already there (from before running the script) or that the password was typed in correctly just before. That doesn't help me to know if I should run
sudo -k at the end or not.
I thought about making two versions of the script, one with and one without
sudo -k, but I don't think that is a nice solution and I am bound to select the wrong version at times.
Is there a better way to solve this? Am I missing something?