Use USB drive as apt-get cache for frequent Raspberry PI reinstalls

I work on a configuration script for a Raspberry Pi, and as I debug it, more often than not I need to run reinstall over and over. On a metered connection it may be a problem, as not only it's slow, it also uses your data plan.

A way around this would be having a local apt-get cache on a removable USB drive. On every install, apt will only fetch the .deb packages from the internet if they're not in the cache, and it will of course save a copy into the cache for future use.

Your USB drive is not a part of the system, so you can safely reinstall your main OS as many times as you want - see /blog/tools/mac-os/clone-raspberry-pi-micro-sd/

0. Format the USB drive

On a Linux machine, simply create ext4 partition.

On a Mac, you may need to format into something both Mac and Linux (your Raspberry OS) will understand, such as ExFAT.

Open Disk Utility and right click your drive, click Erase. Choose:

  • Format: ExFAT
  • Scheme: GUID Partition Map
  • Label (optional): apt-archives, just for fun - yours can be any

Note: If you use ExFAT, apt will show permission errors. A hotfix is to force it to run as root.

echo 'APT::Sandbox::User "root";' > /etc/apt/apt.conf.d/99no-apt-sandbox

1. Permanently mount your USB drive to apt's cache location

Get the UUID for your USB drive. Run lsblk -f and look for the UUID column for your drive. Identify your drive using the label column you defined in the previous step.

mkdir -p /mnt/usb
mkdir -p /mnt/usb/apt-archives
echo 'UUID=697B-9DE4  /mnt/usb  exfat  defaults,nofail,uid=0,gid=0,umask=022,x-systemd.automount  0  0' >> /etc/fstab
echo '/mnt/usb/apt-archives  /var/cache/apt/archives  none  bind,nofail,x-systemd.automount  0  0' >> /etc/fstab

2. Tell apt to NOT clear the cache

echo 'APT::Keep-Downloaded-Packages "true";'  > /etc/apt/apt.conf.d/99keep-debs

3. Reboot and enjoy

To test:

  1. run ls -la /var/cache/apt/archives - note the contents of the folder
  2. run apt-get install something
  3. return to ls -la /var/cache/apt/archives - see the .deb file for your package appear
  4. shut down your RPI and insert the USB drive into your laptop, ensure you can see the .deb package file