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
- -- : A — signals the end of options and disables further option processing for sudo command.
- sh -c : Run sh shell with given commands
- '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." EOFA 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