The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 2,468 other followers

Multiple commands in one sudo: use “sudo sh -c ‘apt update && apt upgrade -y'”

Posted by jpluimers on 2021/09/03

So I won’t forget: [WayBack] @nixcraft on Twitter: Instead of typing the following on your Ubuntu/Debian/Mint Linux desktop: sudo apt update sudo apt upgrade -y Do to save typing and time at the CLI (add to your shell startup): alias update=”sudo sh -c ‘apt update && apt upgrade -y'” See for more info:

[WayBack] How to run multiple commands in sudo under Linux or Unix – nixCraft:

sudo syntax to run multiple commands

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'

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 that shows how to use or run multiple commands with sudo:

#!/bin/bash
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."
EOF

A note about using sudo with bash shell aliases

The syntax is as follows for shell aliases:

alias foo="sudo -- sh -c 'cmd1 && cmd2'"
alias bar='sudo -- sh -c "cmd1 && cmd2"'

–jeroen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: