Thomas Ayoub
Thomas Ayoub

Reputation: 29431

unplug HDD via a bash script

I'm using 2 HDD on my laptop (Mac Os 10.8) and I'd like to automaticaly un-plung the unused one by using a shell script. The problem is that the names (?) can change randomly, today I've got this :

MacBook-Pro-de-Thomas:~ thomas$ diskutil list
/dev/disk0
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *250.1 GB   disk0
   1:                        EFI                         209.7 MB   disk0s1
   2:                  Apple_HFS 10.8                    249.7 GB   disk0s2
/dev/disk1
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *1.0 TB     disk1
   1:                        EFI                         209.7 MB   disk1s1
   2:                  Apple_HFS Mac OS X                870.0 GB   disk1s2
   3:       Microsoft Basic Data Windows                 79.9 GB    disk1s3
   4:       Microsoft Basic Data                         50.0 GB    disk1s4

but at the next reboot they might have switch disk0 and disk1.

I try this script :

diskutil list | grep -e 'disk1s4'
if [$? == 0] 
    then `hdiutil eject disk1`
    else `hdiutil eject disk0`
fi

but something is wrong and I don't know what...

Upvotes: 0

Views: 133

Answers (1)

andrewdotn
andrewdotn

Reputation: 34803

How about this:

  1. Run diskutil list [disk] in a loop over the disk names
  2. For each disk, if it has a partition with “Microsoft” in the name, save the name of the disk to the variable disk_to_eject
  3. After the loop is done, if $disk_to_eject is not empty, eject that disk?

The code would be:

disk_to_eject=
for disk in disk0 disk1; do
    if diskutil list "$disk" | grep -q Microsoft; then
        disk_to_eject="$disk"
    fi
done

if [ -n "$disk_to_eject" ]; then
    hdiutil eject "$disk_to_eject"
fi

Upvotes: 1

Related Questions