Terminal Diskutil – How to Rename USB Stick Using Disk Number

diskutilterminal

I'm creating a bash script that will rename the USB stick using a diskutil command. From what I've read in the man and various examples, I need to supply the volume name.

In my situation, the volume name varies so I'm hoping to use disk number (via diskutil list) instead.

Any ideas on how this can be done?

Best Answer

When you insert a USB drive it automatically gets mounted. You can see the name of the device using the mount command:

$ mount
/dev/disk2 on / (hfs, local, journaled)
devfs on /dev (devfs, local, nobrowse)
map -hosts on /net (autofs, nosuid, automounted, nobrowse)
map auto_home on /home (autofs, automounted, nobrowse)
/dev/disk7s1 on /Volumes/USB-NAME (msdos, local, nodev, nosuid, noowners)

Making the simplifying assumption that you only have one usb drive mounted at a time and it is always formatted with windows, you can then rename the drive like this:

$ diskutil rename $(mount | sed -n '/Volumes.*msdos/{ s/ .*//;p;}') NEW-NAME
Volume on disk7s1 renamed to NEW-NAME

now when you look at the mount output, the name is changed:

$ mount | grep '/Volumes.*msdos'
/dev/disk7s1 on /Volumes/NEW-NAME (msdos, local, nodev, nosuid, noowners)

You may need to adjust the search parameters based on different assumptions, but this is the general idea.