KISS

Keep It Simple Stupid

Unmount flash drive in OS X

| comments

Update on 2012-08-06: Fix the function for a case when a flash drive has no partition table and only one partition.

Fortunately, OS X, as any other unix system, has a lot of command-line tools to control the system. To unmount a USB flash drive you can either right-click on the disk icon on desktop and select Eject (a standard, but mouse-involving thus rather slow method), or use the terminal!

diskutil is the tool to manipulate with disks in OS X. First, to display all the mounted disks and their partitions, type diskutil list. You need to figure out what device your disk is represented with (e.g., /dev/disk1). Then you type diskutil eject /dev/disk1. Done.

This way can be hastened even more, provided you know the disk’s label. Here is the simple function I’ve written for this case:

1
2
3
4
5
6
7
8
9
10
11
12
function unmount() {
  [[ "$1" == "" ]] && {
      echo "No partition's label specified!";
      return -1;
  }
  disk=$(diskutil list | awk 'BEGIN { last_disk="" } /^\/dev\/disk/ { last_disk=$1 } ($2 ~ /'"$1"'/) || ($3 ~ /'"$1"'/) { print last_disk; exit }')
  [[ "$disk" == "" ]] && {
      echo "Disk with this label not found!";
      return -2;
  }
  diskutil eject "$disk"
}

Having added this function to your ~/.profile, ~/.bashrc, or ~/.zshrc (whichever your shell uses), you can issue such a command:

1
$ unmount label

I’ve used this function successfully in zsh, and it should work as well in bash. If you have any issues, please leave a comment.

Comments