How to Unmount all usb pen drive from ubuntu with bash script or terminal? - linux

I want to unmount all pen drive from ubuntu os through a bash script or from a terminal. I knew the command umount /media/MEDIA_NAME, but here we need to specify each MEDIA_NAME. Can I use a single command to unmount from terminal or bash script. Please help me.

Browsing entries in /dev/disk/by-id/ allows you to select USB disks:
for usb_dev in /dev/disk/by-id/usb-*; do
dev=$(readlink -f $usb_dev)
grep -q ^$dev /proc/mounts && umount $dev
done

Loop for each device in the /media directory.
for device in /media/*
do
umount $device
done

Related

How to determine in bash if / mountpoint was mounted from other OS?

Im writing shell script to check if user may be doing some nasty things in Linux enviroment. One check i would like to do is determine if / filesyste was mounted using external OS (like using live SO) in previous mount.
First i think to exec script when boot to get the mount time in previous boot using journalctl and actual last mount using tune2fs, to compare it. But last mount using tune2fs gets current mount, not previous, because system is mounted when ckecks it.
Any idea to solve it?
Thanks!
dmesg's output shows about the mounting of / (and other infos as well). If your current OS's dmesg's output has that info, it was mounted by the current system.
You can use the output of dmesg in your script like :
#!/bin/bash
number=$(dmesg | grep -c "sdaN")
if [ $number == 0 ]; then
echo "It was not mounted by the current system"
else
echo "It was mounted by the current system"
fi

Force unmount of usb drive by closing open applications programatically [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 7 years ago.
Improve this question
When I unplug the AC adapter from my laptop I want all USB drives to automatically unmount. If applications are open that block the device, they should be killed. Once everything is killed and unmount a signal tone could be plaid to indicate that it's now safe to unplug it.
The use case is to quickly grab and go your laptop without having to fumble with the ui to get all drives disconnected but avoid unclean unmounts.
Any hints on how to start would be fantastic, thanks you!
ANSWER
For a full copy&paste script see my answer below.
If your USB devices mount to /mount/media do:
kill -9 $(lsof -t $(mount | grep "/mount/media" | cut -d " " -f 1)) # Exit processes blocking umount cleanly
kill $(lsof -t $(mount | grep "/mount/media" | cut -d " " -f 1)) # Force kill remaining open processes
umount $(mount | grep "/mount/media" | cut -d " " -f 1) # Unmount USB drives
Be careful with this since if you don't have blocking applications open lsof will return all pids and you will kill your running OS. See the copy&paste script below for a working implementation that handles this case.
Then call this script whenever the AC adapter is unplugged by adding this line to /etc/udev/rules.d
SUBSYSTEM=="power_supply", ACTION=="change", ATTR{online}=="0" , RUN+="/path/to/script/shown/above"
The answer below by Nuetrino shows how to detect the AC unplug event, this answer: How do I find out which process is preventing a umount? shows how to list and kill all processes blocking the device from unmounting (I had more success with lsof than fuser -c which sometimes didn't list any processes even though umount was still being blocked)
Details
Use udevadm monitor to log the event, e.g.
KERNEL[20154.545075] change /devices/LNXSYSTM:00/LNXSYBUS:00/ACPI0003:00/power_supply/ADP0 (power_supply)
then use udevadm info -a -p with the event to get the attributes
udevadm info -a -p /devices/LNXSYSTM:00/LNXSYBUS:00/ACPI0003:00/power_supply/ADP0
looking at device '/devices/LNXSYSTM:00/LNXSYBUS:00/ACPI0003:00/power_supply/ADP0':
KERNEL=="ADP0"
SUBSYSTEM=="power_supply"
DRIVER==""
ATTR{online}=="0"
ATTR{type}=="Mains"
Now you can set up the udev rules with the attributes you like as answered below.
You can define udev rules to do it.
Just put your rule in /etc/udev/rules.d
Here is a example from me which i use to control brightness when i remove the AC adapter.
SUBSYSTEM=="power_supply", ACTION=="change", ATTR{online}=="0" , RUN+="/usr/local/bin/bright_unplug"
SUBSYSTEM=="power_supply", ACTION=="change", ATTR{online}=="1" , RUN+="/usr/local/bin/bright_replug
I run my custom script 'bright_replug' and 'bright_unplug' when I recieve kernel uvent.
You can use udevadm monitor to
monitor will print the received events for: UDEV - the event which
udev sends out after rule processing KERNEL - the kernel uevent
You can use udevadm info to match more attributes
Step by step solution
1.
Create this script e.g. in /home/user/uall.sh and replace mount_root with the folder where your distribution mounts usb drives, e.g. /media/user
#!/bin/bash
mount_root=/run/media/user
echo "Try unmounting.."
umount $(ls -d -1 $mount_root/*) # Unmount USB drives
mounted=$(ls -d -1 $mount_root/*) # Probe if there are still applications blocking
if ! [ -z "$mounted" ]
then
echo "Found blocked devices: $mounted, killing.."
kill -9 $(lsof -t $mounted) # Exit processes blocking umount cleanly
kill $(lsof -t $mounted) # Force kill remaining open processes
echo "Unmounting.."
umount $(ls -d -1 $mount_root/*) # Unmount USB drives
mounted=$(ls -d -1 $mount_root/*) # Probe if there are still applications blocking
fi
if [ -z "$mounted" ]
then
echo "Success!"
echo "All USB devices umount."
paplay /usr/share/sounds/speech-dispatcher/test.wav
else
echo "Error!"
echo "Tried it all but couldn't umount all USB devices."
echo "These devices are still mounted:"
echo "$mounted"
fi
2.
Create a udev wrapper script (call it /home/user/uall-udev-wrapper) that executes uall.sh as your username:
#!/bin/bash
runuser -l <user> -c '/home/user/uall.sh > /home/user/uall.log'
3.
Create the file /etc/udev/rules.d/99-usb-unmount.rules with the content
SUBSYSTEM=="power_supply", ACTION=="change", ATTR{online}=="0" , RUN+="/home/user/uall-udev-wrapper"
4.
Reboot or run sudo udevadm control --reload-rules && udevadm trigger to load the new udev rule
Optional. Add an alias uall=/home/user/uall.sh to your ~/.bashrc to access the script easily from your terminal and use your Desktop environment to configure a hotkey to quickly unmount all usb drives
Caveats
1.
When udev runs the script mount will not display gvfsd-fuse mount points, neither will cat /proc/mounts or cat /etc/mtab not even if using the runuser -l <user> wrapper. Instead I'm using now ls -d -1 $mount_root/* which only returns the devices mounted by the current user specified in $mount_root, on a multi user system devices mounted by a different user will not be unmounted by this script.
2.
When udev runs the script I do not get audio from paplay or spd-say.
Any input on these caveats would be greatly appreciated.

In Linux terminal, what would "grep -q '/dev/sda1' /proc/mounts || ..." do?

I want to make a bootable USB device by following this page.
http://planet-lab.org/node/172
It asks me to do these to steps:
umount /dev/sda*
grep -q /dev/sda1 /proc/mounts || dd if=PlanetLab-BootCD-3.3.usb of=/dev/sda1
But it makes me confused.
Since I think /dev/sda is my HDD, I thought it should be unmount /dev/sdb* in order to unmount USB device.
And I really don't understand what grep -q /dev/sda1 /proc/mounts is doing.
It seems to check whether "/dev/sda1" is mounted, but I don't exactly know what are the two parameters of grep command is doing. I know -q is for quiet.
And I also know dd can write an image to a drive.
The instructions state
assuming that the device is detected as /dev/sda
If the assumption is different from the actual mount point, you must modify the commands to match your configuration.
The grep -q is used to test for existence without cluttering the screen with the text which is found. The two parameters are
the text sought "/dev/sda1", and
the file in which the text is sought "/proc/mounts".
In other scripts, you may see something like
grep /dev/sda1 /proc/mounts >/dev/null
to achieve the same effect as the -q option.

Detecting USB Thumb Drive when Ready in Linux Shell Script

I am a Windows admin and dev, I do not generally work with Linux so forgive me if this is in some way obvious.
I have a not so good Linux box, some older version of Open SUSE, and I have a script that unmounts the USB thumb drive, formats it, and then waits for the device to become ready again before it runs a script that does a copy/MD5 checksum verification on the source and destination file to ensure the copy was valid. The problem is that on one box the USB thumb drive does not become ready after the format in a consistent way. It takes anywhere from 1 to 2+ minutes before I can access the drive via /media/LABELNAME.
The direct path is /dev/sdb but, of course, I cannot access it directly via this path to copy the files. Here is my shell script as it stands:
#!/bin/bash
set -e
echo "Starting LABELNAME.\n\nUnmounting /dev/sdb/"
umount /dev/sdb
echo "Formatting /dev/sdb/"
mkfs.vfat -I -F32 -n "LABELNAME" /dev/sdb
echo "Waiting on remount..."
sleep 30
echo "Format complete. Running make master."
perl /home/labelname_master.20120830.pl
Any suggestions? How might I wait for the drive to become ready and detect it? I have seen Detecting and Writing to a USB Key / Thumb DriveAutomatically but quite frankly I don't even know what that answer means.
It seems that you have some automatic mounting service running which detects the flash disk and mounts the partition. However, you already know what the partition is, so I recommend that you simply mount the disk in your script, choosing a suitable mount point yourself.
mkfs.vfat -I -F32 -n "LABELNAME" /dev/sdb
echo "Format complete, remounting"
mount /dev/sdb $mountpoint #<-- you would choose $mountpoint
echo "Running make master."
perl /home/labelname_master.20120830.pl

bash command to force file closure on usb drive

I thought doing a sync in my bash script would force the file to be completely written out. When I looked at the thumb drive, it showed all the files I had copied, but after a power supply failure, the usb drive showed 0 files. Do I have to eject the drive manually or is there something I can do programmatically in my script?
If you want to eject the usb device from your bash script a simple umount on the device should do the trick. For example
mount /dev/usb /mnt/usb
# Your copy operations here... then on success:
umount /mnt/usb
you can also try to use the linux sync instruction that syncronize writing over disk if you're usb key is using a journalized file system

Resources