Linux (Ubuntu): safely remove USB flash disk via command line

Xin Guo picture Xin Guo · Nov 5, 2012 · Viewed 80k times · Source

It would just be cool if your shell script helps you to safely remove your flash disk after finishing its job. I did much homework before posting the question asking for a solution which is expected to meet the following needs:

  1. Suppose the flash disk is mounted as /media/A together with many other flash disks and the code can selectively just remove /media/A without interfering other disks. For example I can pass /media/A as an argument.
  2. A light solution. Installing another package of size 100MB to finish the task drives one crazy.
  3. I know some commands like hdparm except their documents are hard to read. If one can offer me a solution I hope he/she can offer also the explanation of the parameters, etc.
  4. Best if the code can handle all kinds of flash disks (e.g. my old one bought in 2003 with 32Mb) (and portable disks optionally).
  5. It should achieve the exact effect as right clicking the disk --> clicking "safely Remove Drive". The safety concern will prevail, otherwise one may just unplug the disk which usually won't hurt.

Answer

Omnikrys picture Omnikrys · Nov 5, 2012

You can do this using udisks. it is not installed by default but easy enough to install (the package is like a meg in size once installed)...

sudo apt-get install udisks

Once installed you can detach a USB drive with the following commands...

sudo udisks --unmount /dev/sdb1
sudo udisks --detach /dev/sdb

The first line unmounts it. Just like any other partition you can still remount it at this point. The second line detaches it. After this it is powered down and you have to remove/reinsert it to remount.

To clarify sdb is the device and sdb1/2/3/etc are partitions on the device. Also, you will need to unmount all mount points before you attempt to detach the device. Usually with a USB stick/drive there is only one but it is a warning you should know about none the less.

Getting the device name from the mount point would require you pull it from mount or something.