1

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:

[root@localhost ~]# 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))
[root@localhost ~]# echo "$msg"
- nothing here -


[root@localhost ~]# msg=$(mountpoint /u01)
[root@localhost ~]# 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.

Dude
  • 113
  • 1
  • 10

1 Answers1

2

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.

Inian
  • 80,270
  • 14
  • 142
  • 161
  • Yes, redirecting stderr to stdout works for command substitution. But I don't understand the rationale why it is necessary. Isn't it normally that stderr and stdout are redirected to the screen? I see the stderr output on screen when I execute umount via the keyboard. – Dude May 10 '19 at 07:04
  • Anyway thanks a lot for the good tip and example using mountpoint. – Dude May 10 '19 at 07:06
  • 1
    @Dude: It is the general ideology in the Linux world, always separate errors from normal output. Remember both the streams go the terminal tty, but it is just that `$(..)` captures only stdout and not stderr – Inian May 10 '19 at 07:17