Adding files to a raspbian SD card image with simple bash script
There are many elaborate tools out there for building custom raspbian images, and injecting, and adding files. Using just a simple local mount and a bit of bash, you can easily make reproducible raspbian images as well.
Setup Linux Build Server
You’ll need a Linux “build server” to do this. This could be another running Raspberry pi (although it’ll be slow). I used my Fedora workstation. This article doesn’t cover MacOS Bash or Bash for Windows, as it needs losetup
to do the real work.
Create a build directory, and download the latest version of Raspbian;
root@buildserver: mkdir /opt/myraspbian
root@buildserver: mkdir /opt/myraspbian/filesToAdd/
root@buildserver: wget http://raspbian.org/...../2020-02-13-raspbian-buster-lite.img
If it’s not obvious, add your fiiles into the “filesToAdd” directory. The script treats this as a new “root” folder. So if you create filesToAdd/etc/myConfig.ini
on the build server, it will show up as /etc/myConfig.ini
on your built raspbian image.
The Script
#!/bin/bash -v
# Copy the original raspbian image (which starts 2020...) to a new
# building image as we're working on it. cp 2020*.img building.img
# Find partitions on this image and many them available to the
# build server.
losetup --find -P building.img# In the next two steps, we're going to mount the boot partition, then the root partition. They'll be temporarily mounted in $MNT_DIR
MNT_DIR=/mnt/myraspbian# Mount the boot partition, and copy config.txt (that you need
# to create) there. If you don't want to customize config.txt
# then you can delete the next few lines
mkdir -p $MNT_DIR
mount /dev/loop0p1 $MNT_DIR
cp config.txt $MNT_DIR/
umount $MNT_DIR
# Mount the root partition, and copy any files from filesToAdd
# to the partition.
mount /dev/loop0p2 $MNT_DIR
cp -r filesToAdd/* $MNT_DIR/
umount $MNT_DIR # Don't need the loopback device anymore, disconnect it.
losetup -D
# Finished building the image!
mv building.img myraspbian.img
Summary
This is a quick and simple, dirty way to easily add files to a raspbian image. Hope that it works for you!