How to run multiple commands in sudo under Linux or Unix

Posted on in Categories , , , , , , , last updated May 2, 2017

I am a new Linux user. How do I run two commands from a bash shell? I need to run apt-get update and apt-get -y upgrade without typing sudo command two times from a command line on Ubuntu Linux AWS cloud server. How can I two commands in sudo ‘command1 && command2’?

The sudo command used to execute a command as another user typically as a root user. This quick tutorial shows you how to use sudo command to run multiple commands via a Linux or Unix shell.

Fig.01: How to run two commands in sudo?


The syntax is:
sudo sh -c 'command1 && command2'
sudo -- sh -c 'command1 && command2'
sudo -u userNameHere -- sh -c 'command1; command2'
sudo -- sh -c 'command1; command2'
sudo -- bash -c 'command1; command2'
sudo -i -- 'command1; command2; command3'
sudo -i -- sh -c 'command1 && command2 && command3'


Run date and who am i command:
$ sudo -- sh -c 'date; who am i'
Sample outputs:

[sudo] password for vivek: 
Tue May  2 19:52:08 IST 2017
vivek    pts/0        2017-05-02 18:44 (

You can run command as mysql user:
$ sudo -u mysql -- sh -c "/home/mysql/; /home/mysql/"
Update your server in a single go using sudo with the help of apt-get command:
$ sudo -- sh -c 'apt-get update && sudo apt-get -y upgrade'
Sample outputs:

Animated gif 01: sudo command in action
Animated gif 01: sudo command in action

Understanding sudo command options

  1. -- : A — signals the end of options and disables further option processing for sudo command.
  2. sh -c : Run sh shell with given commands
  3. 'apt-get update && sudo apt-get -y upgrade' First update repo and apply upgrades if update was successful.

A note about using sudo command in a shell script

Here is a sample shell script:

echo "Running commands as a root user..."
sudo -- -sh -c <<EOF
apt-get update
apt-get -y upgrade
apt-get -y install nginx 
apt-get -y remove nano
apt-get clean
echo "All done."

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

1 comment

  1. A simpler solution is su root, then run your commands then ^D to get out. Contrary to what some folks say there is nothing intrinsically wrong with conducting commands as root, you just need to take great care, and think before you push key. If your very concerned, put your commands in a shell script and fire that off as root. The more you do stuff the more confident you become.
    best of luck, OBB

Leave a Comment