Bash – If I sudo execute a Bash script file, will all commands inside the Bash script be executed as sudo as well

bashshellshell-scriptsudo

I want to write an automated post-installation script in Bash (called post-install.sh, for instance). The script will automatically add and update repositories, install and update packages, edit config files, etc.

Now, if I execute this script, for instance with sudo post-install.sh, will I only be prompted for a sudo password once, or will I need to enter the sudo password on each invocation of a command inside the script, that needs sudo permission? In other words, do the commands inside the bash script 'inherit' the execution permissions, so to speak?

And, if they indeed do, is there still a possibility that the sudo permissions will time out (if, for instance, a particular command takes long enough to exceed the sudo timeout)? Or will the initial sudo password entrance last for the complete duration of whole script?

Best Answer

Q#1: Will I only be prompted for a sudo password once, or will I need to enter the sudo password on each invocation of a command inside the script, that needs sudo permission?

Yes, once, for the duration of the running of your script.

NOTE: When you provide credentials to sudo, the authentication is typically good for 5 minutes within the shell where you typed the password. Additionally any child processes that get executed from this shell, or any script that runs in the shell (your case) will also run at the elevated level.

Q#2: is there still a possibility that the sudo permissions will time out (if, for instance, a particular command takes long enough to exceed the sudo timeout)? Or will the initial sudo password entrance last for the complete duration of whole script?

No they will not timeout within the script. Only if you interactively were typing them within the shell where the credentials were provided. Every time sudo is executed within this shell, the timeout is reset. But in your case they credentials will remain so long as the script is executing and running commands from within it.

excerpt from sudo man page

This limit is policy-specific; the default password prompt timeout for the sudoers security policy is 5 minutes.