My osupdate script

#!/bin/bash
# original author: pjw@whistl.com
# My internal server is running Ubuntu Linux 18.04 LTS
# with various 16.04 and 18.04 LXD Linux Containers
# I wrote this bash shell script to automate my regular OS software upgrades
# For any containers that are stopped, it starts them up,
# and shuts them down again before quitting

function timestamp() {
 date +%Y-%m-%d-%H:%M:%S
}

# make a list of running and stopped LXD containers, and start all stopped ones
cnlist=""
wasoff=""
for lxclist in $(lxc list -c ns --format csv)
do
  cn=$(echo $lxclist | cut -d, -f1)
  cs=$(echo $lxclist | cut -d, -f2)
  if [ "$cs" == "RUNNING" ]; then
    cnlist="$cnlist $cn"
  elif [ "$cs" == "STOPPED" ]; then
    wasoff="$wasoff $cn"
    echo "$(timestamp) running: lxc start $cn"
    lxc start $cn
  fi
done

# update the host OS first
echo "$(timestamp) running: sudo apt-get -o Acquire::ForceIPv4=true update"
sudo apt-get -o Acquire::ForceIPv4=true update
echo "$(timestamp) running: sudo apt-get -o Acquire::ForceIPv4=true dist-upgrade -y"
sudo apt-get -o Acquire::ForceIPv4=true dist-upgrade -y
echo "$(timestamp) running: sudo apt-get autoremove -y"
sudo apt-get autoremove -y

# upgrade each lxc container, one at a time
# running ones first, wasoff ones later
for cn in $cnlist $wasoff
do
  # wait until the container is online and has a ipv4 address
  ctr=0
  until [ $ctr -ge 60 ]
  do
    cnstat="$(lxc list --format csv -c s $cn)"
    if [ "$cnstat" == "STOPPED" ]
    then
      break
    fi
    cnip="$(lxc list --format csv -c 4 $cn)"
    if [ "$cnstat" == "RUNNING" -a "$cnip" != "" ]
    then
      break
    fi
    mod5=$(( $ctr % 5 ))
    if [ $mod5 -eq 0 ]; then
      echo "$(timestamp) #$ctr $cn: $cnstat $cnip"
    fi
    sleep 1
    ctr=$(( $ctr + 1 ))
  done

  if [ "$cnstat" == "STOPPED" -o $ctr -ge 60 ]; then
    continue
  fi

  echo "$(timestamp) upgrading $cn: $cnstat $cnip"
  echo "$(timestamp) running: lxc exec $cn -- apt-get -o Acquire::ForceIPv4=true update"
  lxc exec $cn -- apt-get -o Acquire::ForceIPv4=true update
  echo "$(timestamp) running: lxc exec $cn -- apt-get -o Acquire::ForceIPv4=true dist-upgrade -y"
  lxc exec $cn -- apt-get -o Acquire::ForceIPv4=true dist-upgrade -y
  echo "$(timestamp) running: lxc exec $cn -- apt-get autoremove -y"
  lxc exec $cn -- apt-get autoremove -y

done

# shutdown the containers that were off before we started
for cn in $wasoff
do
  echo "$(timestamp) running: lxc exec $cn -- shutdown -h now"
  lxc exec $cn -- shutdown -h now
done

echo "$(timestamp) done"
exit 0