I am trying to write an is_device_mounted
script, which in turn will serve a greater purpose in my home Linux system.
It does not even have an error reporting function included and as you can see, I have made it clean for readers. My intention here is to review the code for general Linux. But if you are on a *BSD, I would appreciate your feedback too!
The first version of the script follows:
#!/bin/sh
set -eu
is_empty_string() { [ -z "${1}" ]; }
sanitize_device_string() { printf '%s' "${1}" | grep '^/dev/' | head -n 1; }
is_block_device() { [ -b "${1}" ]; }
is_device_uuid_identified() { printf '%s' "${1}" | grep -F '/by-uuid/'; }
translate_uuid_to_device_name() { readlink -f -n /dev/disk/by-uuid/"${1}"; }
is_device_mounted()
{
if [ -n "${device_name}" ]; then
# 1. basic regex should be working across platforms
# tested on FreeBSD, OpenBSD, NetBSD with success
# I prefer the starting with (^) rather than filtering through all text
# 2. /proc/mounts is not available on all *BSDs, needs revision
proc_mounts=$( grep "^${device_name} " /proc/mounts )
[ -n "${proc_mounts}" ]
fi
}
[ "${#}" -ne 1 ] && { echo "Invalid number of arguments."; exit 1; }
readonly raw_input_string=${1}
is_empty_string "${raw_input_string}" && { echo "The given argument is empty."; exit 1; }
readonly device_string=$( sanitize_device_string "${raw_input_string}" )
is_empty_string "${device_string}" && { echo "The given argument is not a device path."; exit 1; }
! is_block_device "${device_string}" && { echo "The given argument is not a block device."; exit 1; }
readonly block_device=${device_string}
if is_device_uuid_identified "${block_device}"
then
readonly device_name=$( translate_uuid_to_device_name "${block_device}" )
else
readonly device_name=${block_device}
fi
if is_device_mounted "${device_name}"
then
echo "The device: ${block_device} IS mounted."
else
echo "The device: ${block_device} IS NOT mounted."
fi