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

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.


bash and all of its child processes will run with superuser permissions. So you will not need to re-enter a password for commands in your bash script.

The sudo timeout only applies to (later) separate invocation of sudo. It would not affect your already running bash process, or any of its descendants.


These answers are all probably correct. However, this is not the generally-used way (as far as I am aware) to create bash scripts that require sudo permissions. Generally, at the top of the script you assume it hasn't been run with sudo permissions and instead call sudo -v yourself (which will prompt the user for their password) to 'set up' a sudo 'session'. You can either echo some explanatory text before the prompt, or override sudo's own prompt with the -p switch, to let the user know you need sudo access for some commands.

Then, in your script you should be fine to call sudo on the commands that require it (and only those commands that require it) without further password requests. If you think a certain group of commands that run together in your script (regardless of their own use of sudo) will extend beyond the sudo timeout, you can call sudo -v in the middle in order to issue a kind of 'keep-alive' the sudo 'session'.

If the sudo 'session' does happen to expire during the script, the user will simply be asked for their password the next time you issue a sudo command in the script.