Simple Script to Update Ubuntu on CLI

2 min read

Updating Ubuntu using the CLI is done by typing the commands one-by-one or combining the commands using the && operator, i.e. sudo apt update && sudo apt upgrade. Running multiple servers and having to update them by typing out the apt commands over and over can be repetitious so writing a simple script can save some time and stop from misspelling commands. The following will simplify updating your Ubuntu servers.

Update Script

This script is currently being used on Ubuntu 18.04 20.04 22.04. You can choose to uncomment the option to refresh snap if you use it on your system. Create a file using your text editor, I use nano editor.

touch updateos
nano -w updateos

Copy the script into the editor.

#!/bin/bash

# Use: sudo updateos [Option]
# Option: upgrade, dist-upgrade,full-upgrade, default=[upgrade]
# Example: sudo updateos upgrade

# Check if root
if [[ $EUID -ne 0 ]]; then
     echo "You forgot sudo"
     exit 1
fi
# Check for option
if [ -z $1 ]; then
    upgoption="upgrade"
elif [ -n $1 ]; then
     case $1 in
       "dist-upgrade")
          upgoption="dist-upgrade"
          ;;
       "full-upgrade")
          upgoption="full-upgrade"
          ;;
       *)
          echo "Invalid Statement"
          exit
          ;;
     esac
else
     echo "Sum Ting Wong"
     exit
fi
# Going for it
echo "Starting Update"
sudo apt update
echo "Starting " $upgoption
sudo apt $upgoption
echo "Checking for orphaned dependencies..."
sudo apt autoremove
#sudo snap refresh
# Check if need reboot
RESTART_NEEDED=/var/run/reboot-required
if [ -f "$RESTART_NEEDED" ]; then
    echo "Update Complete"
    echo "Restart Required"
    read -p "Would you like to reboot now?(Y/n)" -n 1 -r REEBOOT
    reeboot=${REEBOOT,,}
    if [[ $reeboot =~ ^(y| ) ]] || [[ -z $reeboot ]]; then
         echo
         sudo reboot
    else
         echo
    fi
else
   echo "Update Complete"
   echo "No Restart Required"
fi

Save the file. Example in nano: ctrl+o and ctrl+x

Then switch to a root shell to move the script file, set permissions, and set owner.

sudo -s
mv updateos /usr/bin/
chmod +x /usr/bin/updateos
chmod 0750 /usr/bin/updateos
chown root:root /usr/bin/updateos

Once the above is done, type exit at the command prompt to exit the root shell and back into your user shell. Type the new command updateos and the server will execute the apt & optional snap commands. More experienced users can add commands to run additional updates in the script.

Reference

https://nationalpost.com/news/sum-ting-wong-intern-blamed-for-leaking-fake-names-of-pilots-aboard-plane-that-crashed-in-san-francisco

https://www.tutorialspoint.com/unix/shell_scripting.htm

0
Would love your thoughts, please comment.x
()
x