Bash umount command substitution

Asked by At

I'm running RHEL 7 and bash here. It seems command substitution does not work for the umount command. It does, however, work as usual for other commands. For example:

[[email protected] ~]# msg=$(umount /u01)
umount: /u01: target is busy.
        (In some cases useful info about processes that use
         the device is found by lsof(8) or fuser(1))
[[email protected] ~]# echo "$msg"
- nothing here -


[[email protected] ~]# msg=$(mountpoint /u01)
[[email protected] ~]# echo "$msg"
/u01 is a mountpoint

What I can probably do is to use mountpoint first and then umount if the mountpoint exists. Then check for umount status - if there is an error I guess the device must be busy.

1 Answers

2
Inian On Best Solutions

It's probably the umount writes those errors to standard error output stream. With command-substitution $(..), you can only capture the standard output stream. The right fix for the same would be

msg="$(umount /u01 2>&1)"

But instead of relying on the verbose information, you can rely on the exit codes of those commands, i.e. first check

if mountpoint /u01 2>&1 > /dev/null; then
    if ! umount /u01 2>&1 > /dev/null; then
        printf '%s\n' "/u01 device must be busy"
    else
        printf '%s\n' "/u01 device is mounted"
    fi
fi

The above version safely nullifies the output strings produced by both those commands, and only prints the mount status of the device. The part 2>&1 >/dev/null in short means, re-direct all standard error to standard output and combined put them to the null device, so that they are visible on the terminal window.