When using && and sudo on the first command, is the second command run as sudo too?

TL;DR: NO


The first command is

sudo some-command

The second command is

some-other-command

The command sudo takes the following command and executes it with elevated privileges. The &&, however, doesn't belong to a command and is interpreted by the shell, before executing the first command. It tells bash to first execute the first command, and on success the second one.

So the sudo doesn't know about the && some-other command. When the elevated process terminates, bash takes its return value, and then executes the other command, which again doesn't know of the first one.

This can be demonstrated easily:

$ sudo whoami && whoami
root
username

To reach what you want, you can start an elevated bash, and let it execute both commands:

$ sudo bash -c 'whoami && whoami'
root
root

So now, both commands are executed as root, as the whole process described above is executed in an elevated process, i.e. the bash session started with this command, which immediately exits after finishing. Still, the both whoamis don't know of each others existence.

This does not suit any purpose but for this demonstration, the easier way is to simply do

sudo some-command && sudo some-other-command

No. Some examples that do this are:

sudo some-command && sudo some-other-command 
sudo sh -c "some-command && some-other-command"

or if you want nest commands you can even do:

sudo bash <<"EOF"
some-command
some-other-command
sudo bash <<"EOF2"
    some-command2
    some-other-command2
EOF2
EOF
  • The 2nd uses another shell.
  • Mind that when you use ' or " in the 2nd version you need to escape those in the commands or parameters of that command (ie. \' or \") so that can get complex very quickly.

No, either you must write sudo twice, or do something like

sudo bash -c 'foo && bar'