2015-02-24

Command line to power off portable harddisk / usb drive on Linux

Sometimes we plug and mount a portable harddisk or USB on Linux server and want to unplug it using command line :3 script ninja! You can use udisks comand to do this, just find which drive are your portable disk attached as, for example using lsblkfdisk, or df command

$ lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 931.5G  0 disk 
└─sda1   8:1    0 931.5G  0 part 
sdb      8:16   0 458.6G  0 disk 
├─sdb1   8:17   0     1G  0 part /boot
├─sdb2   8:18   0     2G  0 part [SWAP]
├─sdb3   8:19   0    64G  0 part /
└─sdb4   8:20   0 391.6G  0 part /home
sr0     11:0    1  1024M  0 rom  

$ fdisk -l 
Disk /dev/sdb: 458.6 GiB, 492387172352 bytes, 961693696 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xc5900613

Device     Boot     Start       End   Sectors   Size Id Type
/dev/sdb1  *           63   2104514   2104452     1G 83 Linux
/dev/sdb2         2104515   6313544   4209030     2G 82 Linux swap / Solaris
/dev/sdb3         6313545 140536619 134223075    64G 83 Linux
/dev/sdb4       140536620 961683029 821146410 391.6G 83 Linux

Disk /dev/sda: 931.5 GiB, 1000204885504 bytes, 1953525167 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 33553920 bytes
Disklabel type: dos
Disk identifier: 0x9a70439c

Device     Boot Start        End    Sectors   Size Id Type
/dev/sda1        2048 1953521663 1953519616 931.5G  7 HPFS/NTFS/exFAT

$ df | grep -v tmpfs
Filesystem     Type     1M-blocks  Used Available Use% Mounted on
/dev/sdb3      ext4         64381 33387     27701  55% /
/dev/sdb1      ext2          1012    40       921   5% /boot
/dev/sdb4      ext4        394531 59129    315339  16% /home

$ cat /proc/partitions 
major minor  #blocks  name
   8       16  480846848 sdb
   8       17    1052226 sdb1
   8       18    2104515 sdb2
   8       19   67111537 sdb3
   8       20  410573205 sdb4
  11        0    1048575 sr0
   8        0  976762583 sda
   8        1  976759808 sda1

Then just call udisks with --detach flag to safely remove the device, for example:

sudo udisks --detach /dev/sda

Or you can use this script, download/save then you can execute it, for example:

sudo sh suspend-usb-device.sh -v /dev/sda 

now your portable disk can be removed safely.

Note: if you're using kernel newer than 2.6.32, there would be an error line 180: echo: write error: Invalid argument, change that script on line 180 from suspend into auto. And of course if you have Nemo (or maybe Nautilus too, but not for Thunar) installed you can always right click and then safely remove the drive without command line.


No comments :

Post a Comment

THINK: is it True? is it Helpful? is it Inspiring? is it Necessary? is it Kind?