Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute multiple commands with sudo in script [duplicate]

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
like image 666
Sasikiran Vaddi Avatar asked May 20 '15 06:05

Sasikiran Vaddi


People also ask

Can be used to run multiple commands one after the other?

The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds.


1 Answers

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
'
like image 142
Michał Šrajer Avatar answered Oct 04 '22 14:10

Michał Šrajer