Automatically mounting available partition of SD card

995 views Asked by At
SD card Type Partition available Size of Partition
A mmcblk0p1, mmcblk0p2 mmcblk0p1: 30Mb, mmcblk0p2: 31Gb
B mmcblk0p1 mmcblk0p1: 31Gb

I am using a linux system where I need to mount the largest available SD card partition block automatically during boot. I am able to mount a specific partition eg. /dev/mmcblk0p2 by adjusting /etc/fstab. But this does not work if I change the type of SD card, eg. using type B SD card instead of type A.

Is there a way to mount the largest available partition block automatically irrespective of the type used?.

Type is simply used here for explanation purpose. Basically type A is a formatted SD with burned images whereas type B is fresh new SD card.

Any feedback or solution will help a lot. Thank you all.

1

There are 1 answers

1
btafarelo On

I made a script and service to achieve it as I was quite interested on this subject.

The script is selecting the largest partition on /dev/sdb, so if your device has another identification it has to be changed to reflect your env.

My environment

  • Ubuntu Server on VirtualBox
  • 8GB USB stick with 2 partitions

The script

Path: /opt/usb_mount_script.sh

#!/bin/bash

partition="/dev/$(lsblk -x size -i -n | grep -Po 'sdb[0-9]+.*' | tail -n 1 | cut -d ' ' -f 1)"

sudo mount "$partition" /mnt/usb_largest_partition

exit 0

Explanation

  • lsblk -x size -i -n => list all partitions, sort by size, ASCII mode and no header
  • grep -Po 'sdb[0-9]+.*' => filter the partitions by device sdb
  • tail -n 1 => get the last line
  • cut -d ' ' -f 1 => get the partition name

The service

Path: /etc/systemd/system/test.service

[Unit]
Descriptionn=mount largest partition at boot time
After=mnt-wibble.mount

[Service]
Type=simple
ExecStart=/opt/usb_mount_script.sh

[Install]
WantedBy=multi-user.target

Setup

  • create the service
  • create the script
  • allow execution on the script: sudo chmod +x usb_mount_script.sh
  • create the mount dir: mkdir /mnt/usb_largest_partition
  • install the service: sudo systemctl enable test
  • run the service manually with systemctl start test
  • boot up your system with the sdcard/usb plugged in