You have to run a check to see if is mounted already, then determine to mount based on the conditional.
In your case, it's /dev/sdc.
#!/bin/bash
# Function to check state of the USB drive
function is_usb_ready() {
# Check if the USB drive exists
if lsblk -d -o NAME | grep -q "^sdc$"; then
# Check if the USB drive is not mounted
if ! mount | grep -q "/dev/sdc"; then
return 0 # Plugged in and not mounted
fi
fi
return 1 # Not plugged in or already mounted
}
# Call function and perform the proper task based on its return value
if is_usb_ready; then
echo "USB drive exists, but not mounted. Mounting drive."
sudo mount /dev/sdc /your/mount_point/here
else
echo "USB drive is not plugged in or already mounted."
fi
# Rest of your code
exit 0
The first grep will check if the drive's already plugged in, and the second grep will determine if it's mounted. If not, do so, otherwise proceed.
This is a way to do the check via destination instead of source. Since both don't cover each other's potential scenario's, I'll put both, and leave the decision up to the user.
#!/bin/bash
mountpoint="/your/mount_point/here"
function is_usb_ready() {
# Check for filesystem at the mount point
if mountpoint -q "$mountpoint"; then
echo "The USB drive is already mounted at $mountpoint."
return 1 # Already mounted
else
# If not mounted, check for device
if lsblk -d -o NAME,TRAN | grep -q "sdc.*usb"; then
return 0 # USB drive exists and is not mounted
fi
fi
return 1 # USB drive is not plugged in
}
# Call function and perform the proper task based on its return value
if is_usb_ready; then
echo "USB drive exists, but not mounted. Mounting drive."
# Mount the USB drive
sudo mount /dev/sdc "$mountpoint"
else
echo "USB drive is not plugged in or already mounted."
fi
# Rest of your code
exit 0
It's waltinator for the win! A very simple solution.
#!/bin/bash
mountpoint="/your/mount_point/here"
if sudo grep -q "$mountpoint" /etc/mtab; then
echo "The USB drive is already mounted at $mountpoint."
else
echo "Mounting the USB drive."
sudo mount /dev/sdc "$mountpoint"
fi
# Rest of your code
exit 0
set -eor a first#!line that includes the-eflag?set -ehelps in skipping errors? Thanks for your time.-ecauses the script to exit if an error occurs (although its definition of what's an error is weird). You almost certainly do not want-emode set in your script. See BashFAQ#105: "Why doesn't set -e (or set -o errexit, or trap ERR) do what I expected?"