Creating a uSD image from a file tree

This article illustrates how to create a bootable Linux microSD image starting from a file tree

Sometimes could be useful to create a uSD bootable image starting directly from the file tree generated by Debian Multistrap or Buildroot scripts.

A bootable image can be distributed directly to Mac or Windows users those can generate in this way bootable uSD even if they cannot write in ext4 format directly.

Step by step procedure

Create a regular file as large as the total size of your file tree. In this example we will create a 1GB file:

$ dd if=/dev/zero of=myimage.img bs=512 count=1953125
1953125+0 records in
1953125+0 records out
1000000000 bytes (1.0 GB) copied, 1.80442 s, 554 MB/s

Associate the first free loop device (-f option) to the regular file and show the loop device used (--show option):

$ sudo losetup -f --show myimage.img

Create two partitions:

$ sudo parted -s /dev/loop0 mklabel msdos
$ sudo parted -s /dev/loop0 mkpart primary fat32 4 128
$ sudo parted -s /dev/loop0 mkpart primary ext4 128 100%
$ sudo parted -s /dev/loop0 set 1 boot on
$ sudo parted -s /dev/loop0 print
$ sudo partprobe /dev/loop0
$ sudo kpartx -s -a /dev/loop0

Create the filesystems inside the partitions:

$ sudo mkfs -t vfat -n boot /dev/mapper/loop0p1
$ sudo mkfs -F -t ext4 -L rootfs /dev/mapper/loop0p2
$ sync

Mount the new filesystems:

$ mkdir mnt
$ mkdir mnt/boot
$ mkdir mnt/rootfs
$ sudo mount -t vfat /dev/mapper/loop0p1 mnt/boot
$ sudo mount -t ext4 /dev/mapper/loop0p2 mnt/rootfs

Now copy the file tree inside mnt/boot and mnt/rootfs

Then umount the disks type:

$ sudo umount mnt/boot
$ sudo umount mnt/rootfs
$ sudo losetup -d /dev/loop0
$ sync

Now the myimage.img file is ready to be written on uSD card

$ sudo dd if=myimage.img of=sdb


Sergio Tanzilli - -