On Wed, Jul 01, 2026 at 20:40:30 +0200, Franco Martelli wrote:
> In addiction I'd suggest to use the so called "exit status variable: $?" in
> the "if ; then" statement:
>
> ...
> echo "working volume assigned a value; now try blkid."
> blkid -t UUID="$workingVolume" >/dev/null 2>&1
> if [ $? -ne 0 ] ; then
> printf "workingVolume not found.\n"
> else
> ...
>
> it makes the code more readable, IMHO.
I disagree, but of course this is an opinion, and you're entitled to
feel this way.
In the general case where you want to run a command, and print an error
message of your own if it fails, inside of a function, I would probably
use this format:
checkvolume() {
local workingVolume=...
blkid -t UUID="$workingVolume" >/dev/null 2>&1 || {
echo "working volume not found" >&2
return 1
}
...
}
However, in this *specific* example, the OP is actually calling blkid
twice -- once to check whether it succeeds, then again to get the output
and parse it. I would reduce that to a single call instead. Then it
becomes more "interesting" to extract the exit status. Assuming we're
using bash, and not sh, we can use pipefail:
checkvolume() {
local workingVolume=...
local device
device=$(set -o pipefail;
blkid -t UUID="$workingVolume" 2>/dev/null | cut -d: -f1) || {
echo "working volume not found" >&2
return 1
}
printf "working volume found: device is '%s'\n" "$device"
...
}
Otherwise, if we're using sh, the best solution is probably to store
the full output of lsblk, and then parse it in a second pass. In fact,
this may even be preferred in bash.
checkvolume() {
# use local if your shell has it
workingVolume=...
device=$(blkid -t UUID="$workingVolume" 2>/dev/null) || {
echo "working volume not found" >&2
return 1
}
device=${device%%:*}
printf "working volume found: device is '%s'\n" "$device"
...
}
That's probably the cleanest version.