How to execute multiple commands with sudo in script

Sasikiran Vaddi picture Sasikiran Vaddi · May 20, 2015 · Viewed 8.3k times · Source

Can we use heredocs to run multiple commands using sudo?

I am facing an issue (need to pass password for every command) while running multiple commands:

echo 'password'| sudo -S ls
echo 'password'| sudo -S cat /var/log/abc.log

Can anyone help me how to automate this in a script? Like:

echo 'password' | sudo -S << ENDBLOCK
ls
cat
ENDBLOCK

Answer

Michał Šrajer picture Michał Šrajer · May 20, 2015

you can run sh -c ..., but remember to quote properly.

sudo sh -c 'id; echo another command ; id'

sudo must see this as a single argument for the sh command.

Of course you can use new line instead of semicolon:

sudo sh -c '
  echo "I am root"
  id
  echo "another command"
  id
'