Detect and mount USB devices in Linux from console

Pendrive usage with Linux
Image: Pendrive usage with Linux (License: CC-BY-SA Marcelo Canina)

Mount pendrives with commands in the Linux terminal

Published:
Last modified:

Overview

This is a small guide to detect a newly attached device to an USB port and mount it in Linux.

We will explore different strategies that will help when some of the tools isn’t available.

First of all, some definitions:

Understanding

What does exactly mount means?

All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices. The mount command serves to attach the filesystem found on some device to the big file tree. Conversely, the umount(8) command will detach it again. The filesystem is used to control how data is stored on the device or provided in a virtual way by network or another services.

To attach these new devices filesystems we use the mount command in the form: mount -t type device dir.

In the above command, Devices (block special devices1) can be indicated in one of the following three ways:

  1. Filename
    • using the filename that is associated with the device.
    • e.g.: /dev/sdb2
  2. Filesystem label
    • Using the label associated with the device.
    • e.g.: PENDRIVE
  3. UUID
    • Universally Unique IDentifier (UUID) Uniform Resource Namespace 2.
    • e.g.: ba108o135-80bf-1cci-b2za-082eafd02y0g

Listing

To list the currently mounted devices/filesystems, findmnt.

For example, in Ubuntu 18.10 it shows:


$ findmnt
TARGET                                SOURCE           FSTYPE        OPTIONS
/                                     /dev/mmcblk0p3   ext4          rw,relatime,errors=remount-ro
β”œβ”€/sys                                sysfs            sysfs         rw,nosuid,nodev,noexec,relatime
β”‚ β”œβ”€/sys/kernel/security              securityfs       securityfs    rw,nosuid,nodev,noexec,relatime
β”‚ β”œβ”€/sys/fs/cgroup                    tmpfs            tmpfs         ro,nosuid,nodev,noexec,mode=755
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/unified          cgroup2          cgroup2       rw,nosuid,nodev,noexec,relatime,nsdelegate
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/systemd          cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,xattr,name=systemd
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/cpu,cpuacct      cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,cpu,cpuacct
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/hugetlb          cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,hugetlb
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/blkio            cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,blkio
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/memory           cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,memory
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/devices          cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,devices
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/net_cls,net_prio cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,net_cls,net_prio
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/cpuset           cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,cpuset
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/freezer          cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,freezer
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/pids             cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,pids
β”‚ β”‚ β”œβ”€/sys/fs/cgroup/perf_event       cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,perf_event
β”‚ β”‚ └─/sys/fs/cgroup/rdma             cgroup           cgroup        rw,nosuid,nodev,noexec,relatime,rdma
β”‚ β”œβ”€/sys/fs/pstore                    pstore           pstore        rw,nosuid,nodev,noexec,relatime
β”‚ β”œβ”€/sys/firmware/efi/efivars         efivarfs         efivarfs      rw,nosuid,nodev,noexec,relatime
β”‚ β”œβ”€/sys/fs/bpf                       bpf              bpf           rw,nosuid,nodev,noexec,relatime,mode=700
β”‚ β”œβ”€/sys/kernel/debug                 debugfs          debugfs       rw,relatime
β”‚ β”œβ”€/sys/fs/fuse/connections          fusectl          fusectl       rw,relatime
β”‚ └─/sys/kernel/config                configfs         configfs      rw,relatime
β”œβ”€/proc                               proc             proc          rw,nosuid,nodev,noexec,relatime
β”‚ └─/proc/sys/fs/binfmt_misc          systemd-1        autofs        rw,relatime,fd=33,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=16216
β”œβ”€/dev                                udev             devtmpfs      rw,nosuid,relatime,size=931092k,nr_inodes=232773,mode=755
β”‚ β”œβ”€/dev/pts                          devpts           devpts        rw,nosuid,noexec,relatime,gid=5,mode=620,ptmxmode=000
β”‚ β”œβ”€/dev/shm                          tmpfs            tmpfs         rw,nosuid,nodev
β”‚ β”œβ”€/dev/hugepages                    hugetlbfs        hugetlbfs     rw,relatime,pagesize=2M
β”‚ └─/dev/mqueue                       mqueue           mqueue        rw,relatime
β”œβ”€/run                                tmpfs            tmpfs         rw,nosuid,noexec,relatime,size=192560k,mode=755
β”‚ β”œβ”€/run/lock                         tmpfs            tmpfs         rw,nosuid,nodev,noexec,relatime,size=5120k
β”‚ β”œβ”€/run/snapd/ns                     tmpfs[/snapd/ns] tmpfs         rw,nosuid,noexec,relatime,size=192560k,mode=755
β”‚ β”‚ └─/run/snapd/ns/hugo.mnt          nsfs[mnt:[4026532555]]
β”‚ β”‚                                                    nsfs          rw
β”‚ └─/run/user/1000                    tmpfs            tmpfs         rw,nosuid,nodev,relatime,size=192556k,mode=700,uid=1000,gid=1000
β”‚   └─/run/user/1000/gvfs             gvfsd-fuse       fuse.gvfsd-fu rw,nosuid,nodev,relatime,user_id=1000,group_id=1000
β”œβ”€/snap/gnome-logs/45                 /dev/loop0       squashfs      ro,nodev,relatime
β”œβ”€/snap/tree/15                       /dev/loop1       squashfs      ro,nodev,relatime
β”œβ”€/snap/gnome-characters/139          /dev/loop2       squashfs      ro,nodev,relatime
β”œβ”€/snap/core/6130                     /dev/loop3       squashfs      ro,nodev,relatime
β”œβ”€/snap/gnome-3-26-1604/74            /dev/loop5       squashfs      ro,nodev,relatime
β”œβ”€/snap/node/1544                     /dev/loop4       squashfs      ro,nodev,relatime
β”œβ”€/snap/gnome-characters/124          /dev/loop6       squashfs      ro,nodev,relatime
β”œβ”€/snap/gtk-common-themes/701         /dev/loop7       squashfs      ro,nodev,relatime
β”œβ”€/snap/gnome-3-26-1604/70            /dev/loop8       squashfs      ro,nodev,relatime
β”œβ”€/snap/core/5662                     /dev/loop9       squashfs      ro,nodev,relatime
β”œβ”€/snap/heroku/3685                   /dev/loop10      squashfs      ro,nodev,relatime
β”œβ”€/snap/hugo/3565                     /dev/loop11      squashfs      ro,nodev,relatime
β”œβ”€/snap/gtk-common-themes/818         /dev/loop12      squashfs      ro,nodev,relatime
└─/boot/efi                           /dev/mmcblk0p1   vfat          rw,relatime,fmask=0077,dmask=0077,codepage=437,iocharset=iso8859-1,shortname=mi

There is also the old way, maintained for compatibility only but widely used: mount -l or just mount.

Now we have just connected a pendrive, how do we know which label or UUID it has to be able to mount the filesystem?

1. Identify the newly attached device

After we plug a pendrive, we need a method to locate the new device so we can get its label or UUID.

The following list shows the available alternatives to do it, any of them would be help you find the device information, listing most complete and easier to use first.

1.1 Using blk commands

The command lsblk prints all block devices (except RAM disks) in a tree-like format by default.

We can have a look at it to try to spot the new device with the filesystem parameter: --fs to print info of each filesystem, LABELs and UUIDs on available block devices.

Example output:


$ lsblk --fs
NAME         FSTYPE   LABEL              UUID                                 MOUNTPOINT
loop0        squashfs                                                         /snap/gnome-logs/45
loop1        squashfs                                                         /snap/tree/15
loop2        squashfs                                                         /snap/gnome-characters/139
loop3        squashfs                                                         /snap/core/6130
loop4        squashfs                                                         /snap/node/1544
loop5        squashfs                                                         /snap/gnome-3-26-1604/74
loop6        squashfs                                                         /snap/gnome-characters/124
loop7        squashfs                                                         /snap/gtk-common-themes/701
loop8        squashfs                                                         /snap/gnome-3-26-1604/70
loop9        squashfs                                                         /snap/core/5662
loop10       squashfs                                                         /snap/heroku/3685
loop11       squashfs                                                         /snap/hugo/3565
loop12       squashfs                                                         /snap/gtk-common-themes/818
sda          iso9660  Ubuntu 18.10 amd64 2018-XX-XX-XX-44-30-00               
β”œβ”€sda1       iso9660  Ubuntu 18.10 amd64 2018-XX-XX-XX-44-30-00               
└─sda2       vfat     Ubuntu 18.10 amd64 B29B-M89B                            
mmcblk0                                                                       
β”œβ”€mmcblk0p1  vfat                        DXXX-1XXX                             /boot/efi
β”œβ”€mmcblk0p2  ext4                        a1031234-80bf-2xds-ba5a-05asdlfk824c3 /home
└─mmcblk0p3  ext4                        34asdf82-248n-g8us-fs56-jdfskf8401b25 /
mmcblk0boot0                                                                  
mmcblk0boot1                                

To directly find out the connected pendrive, save the above listing in a temporal folder and then look for the differences with the same command after plugging the pendrive:


$ lsblk --fs >/tmp/nousb.txt
$ # plug usb
$ lsblk --fs >/tmp/withusb.txt
$ diff --ignore-space-change /tmp/withusb.txt /tmp/nousb.txt
15,17d14
sda          iso9660  Ubuntu 18.10 amd64 2018-XX-XX-XX-44-30-00
β”œβ”€sda1       iso9660  Ubuntu 18.10 amd64 2018-XX-XX-XX-44-30-00
└─sda2       vfat     Ubuntu 18.10 amd64 BXXX-6XXX

1.2 Inspect Kernel ring buffer

Immediately after plugging the device, we can examine the kernel ring buffer with the command dmesg

There we can look for the string of type sda, or sdb, etc, that will belong to the most recent connected device.


$ dmesg | tail
[12548.711522] scsi host0: usb-storage 1-2:1.0
[12549.741820] scsi 0:0:0:0: Direct-Access     Kingston DataTraveler 112 1.00 PQ: 0 ANSI: 2
[12549.743566] sd 0:0:0:0: Attached scsi generic sg0 type 0
[12549.752414] sd 0:0:0:0: [sda] 7831552 512-byte logical blocks: (4.01 GB/3.73 GiB)
[12549.752699] sd 0:0:0:0: [sda] Write Protect is off
[12549.752702] sd 0:0:0:0: [sda] Mode Sense: 23 00 00 00
[12549.752992] sd 0:0:0:0: [sda] No Caching mode page found
[12549.752998] sd 0:0:0:0: [sda] Assuming drive cache: write through
[12550.748224]  sda: sda1 sda2
[12550.751694] sd 0:0:0:0: [sda] Attached SCSI removable disk

In this case we can spot the sda: sda1 sda2 line that indicates it has two partitions: sda1 and sda2.

Then we use the command blkid -p device to find out its UUID, label and more properties.


$ sudo blkid -p /dev/sda1
/dev/sda1: UUID="2018-XX-XX-XX-44-30-00" BOOT_SYSTEM_ID="EL TORITO SPECIFICATION" VERSION="Joliet Extension" LABEL="Ubuntu 18.10 amd64" TYPE="iso9660" USAGE="filesystem" PTUUID="133XXXXe" PTTYPE="dos" PART_ENTRY_SCHEME="dos" PART_ENTRY_UUID="133XXXXe-01" PART_ENTRY_TYPE="0x0" PART_ENTRY_FLAGS="0x80" PART_ENTRY_NUMBER="1" PART_ENTRY_OFFSET="0" PART_ENTRY_SIZE="3905280" PART_ENTRY_DISK="8:0"
$ sudo blkid -p /dev/sda2
/dev/sda2: SEC_TYPE="msdos" UUID="B4XX-XXXA" VERSION="FAT12" TYPE="vfat" USAGE="filesystem" PART_ENTRY_SCHEME="dos" PART_ENTRY_UUID="13XXXXXe-02" PART_ENTRY_TYPE="0xef" PART_ENTRY_NUMBER="2" PART_ENTRY_OFFSET="3828884" PART_ENTRY_SIZE="4928" PART_ENTRY_DISK="8:0"

1.3 dev-by- directories

Inspect the directories: /dev/disk/by-{label,uuid,partuuid,partlabel}.

And a similar approach can be done to know which one was plugged in, saving the list before and after plugging the device:


$ ls -l /dev/disk/by-* >/tmp/nousb.txt
$ # plug usb
$ ls -l /dev/disk/by-* >/tmp/withusb.txt
$ diff --ignore-space-change /tmp/withusb.txt /tmp/nousb.txt
7,13d6
 lrwxrwxrwx   1 root           root      9 2019-01-24 14:18 usb-Kingston_DataTraveler_112_001XXXXXXXXXXXXXXXXXXX69-0:0 -> ../../sda
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 usb-Kingston_DataTraveler_112_001XXXXXXXXXXXXXXXXXXX69-0:0-part1 -> ../../sda1
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 usb-Kingston_DataTraveler_112_001XXXXXXXXXXXXXXXXXXX69-0:0-part2 -> ../../sda2
 
 /dev/disk/by-label/:
 total 0
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 Ubuntu\x2018.10\x20amd64 -> ../../sda2
17,18d9
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 13XXXXe-01 -> ../../sda1
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 13XXXXe-02 -> ../../sda2
25,27d15
 lrwxrwxrwx   1 root           root      9 2019-01-24 14:18 pci-0000:00:14.0-usb-0:2:1.0-scsi-0:0:0:0 -> ../../sda
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 pci-0000:00:14.0-usb-0:2:1.0-scsi-0:0:0:0-part1 -> ../../sda1
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 pci-0000:00:14.0-usb-0:2:1.0-scsi-0:0:0:0-part2 -> ../../sda2
37d24
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 2018-10-17-22-44-30-00 -> ../../sda1
39d25
 lrwxrwxrwx   1 root           root     10 2019-01-24 14:18 BXXX-6XXX -> ../../sda2

These directories should be avoided at `fstab` in favor of `UUID`.

2. Mount the device

Which method should we use?

The device name of disk partitions are unstable.

They depend on what (physical) slot you connect the device, and if there are other devices already attached or not, so the filename to refer to them may change over time.

Labels are more stable than filenames, but they may change or have the same name as other label.

The best way to mount a device is using the UUID, as you can be sure it won’t change over time.

We will mount it at /media/usb-stick.

Create directory: sudo mkdir /media/usb-stick

And mount it with one of these methods, preferably UUID:

sudo mount -t auto /dev/sda2 /media/usb-stick/

# mount using label
# mount -L label
sudo mount -L Ubuntu 18.10

# mount using UUID
# mount -U uuid
sudo mount -U BXXX-6XXX

3. Make it permanent

There is a special file /etc/fstab, that each line describes:

  • what devices are usually mounted
  • where,
  • using which options

After reboot each line will be mounted automatically if the device is connected.

As we are working mostly with pendrives, we should use the special option: nofail. This avoids reporting any errors for the device if it does not exist at booting time when it tries to mount them and probably the device won’t be plugged..

If you don't add the nofail option, your system would have some problems during booting time, where you should comment the added lines to /etc/fstab

Here we use the UUID to be sure we always refer to the same device.

In /etc/fstab:

# pendrive negro kingston 2gb
UUID=2018-XX-XX-XX-44-30-00               /media/usb-stick auto defaults,nofail

3.1 Mount a pendrive just by specifying a directory

Now that fstab knows that our USB-stick should be placed at /media/usb-stick, we can mount the pendrive just by using that directory the next time we plug the pendrive:

mount /media/usb-stick

Personally, I like to have each pendrive or device identified like /media/kingstone-2gb so I can easily mount it with the directory name after plugging it.

4. Remove pendrive

When you want To finally remove the USB-stick, you need to release it from the filesystem first with umount.

sudo umount /media/usb-stick

Optional

Set pendrive label

To set create or rename the label of a pendrive there are several programs:

  • e2label - Change the label on an ext2/ext3/ext4 filesystem
  • tune2fs - adjust tunable filesystem parameters on ext2/ext3/ext4 filesystems
  • mke2fs - create an ext2/ext3/ext4 filesystem

To set a pendrive label as usb-stick

e2label /dev/sda1 usb-stick
tune2fs -L usb-stick /dev/sda1

Or create filesystem:

mke2fs	pubsw /dev/hdb1

And change the label

mke2fs -L	pubsw /dev/hdb1

Summary

Summarizing the commands used above in a single list:

# find filesystem / list mount points
findmnt
# print info about all block device filesystems 
lsblk --fs
#look for UUID
mount -t auto -U XXXXXXXXXXX

Resources


  1. block special file: A block special file is normally distinguished from a character special file by providing access to the device in a manner such that the hardware characteristics of the device are not visible. http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_79

    [return]
  2. A Universally Unique IDentifier (UUID) URN Namespace https://tools.ietf.org/html/rfc4122 [return]
Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

Β·