Even though the path exists, this script reports that it does not. What is the flaw in the logic?


if grep -qs "$mount" /proc/mount && { test -d '/fileserver/subdirectory'; } then
 echo "Both the mount and path exist."
else grep -qs "$mount" /proc/mount ! && { test -d '/fileserver/subdirectory'; }
 echo "mount exists, but path does not."

The idea is quite right, but the negation operator to use along with the && is in wrong place altogether, it needs to be alongside the test operator.

With your command in question the first part of the if condition is evaluated as below,

grep -qs "$mount" /proc/mount !

in which the negation operator is treated as an another file to search on by the grep which would have resulted in grep: !: No such file or directory, but because of the error suppress flags on file non-existence (-s) the errors are not shown in the terminal.

Also the {..} compound operator is not needed as long as you have a single command. You just need to do below:

if grep -qs "$mount" /proc/mount &&  test -d "/fileserver/subdirectory";  then
    echo "Both the mount and path exist."
else grep -qs "$mount" /proc/mount && ! test -d "/fileserver/subdirectory"; then
    echo "mount exists, but path does not."

That said, you don't need to silence the output of grep right away until you assert the script is working. Try running it without the -qs flags for an added debug step.

You can also use mountpoint(1) tool from the util-linux package using which you can directly check if a path is mounted

if mountpath -q "/fileserver/subdirectory"; then
  • 1
    Very good, @inian. +1. I would also point out (1) while in the process of debugging code, it is best not to silence the error messages as the -qs options do on the grep command, and (2) on Linux, mountpoint -q "$mount" is generally superior to grepping /proc/mount. (mountpoint is part of the util-linux package.) – John1024 May 23 at 6:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.