How to use read timeouts with stat?

I have the following code:

#!/bin/bash read -t1 < <(stat -t "/my/mountpoint") if [ $? -eq 1 ]; then echo NFS mount stale. Removing... umount -f -l /my/mountpoint fi 

How to disable the output of statistics, and at the same time, you can still determine the level of error in the subsequent test?

Adding >/dev/null 2>&1 inside a subshell or at the end of a read line does not work. But there must be a way ...

Thanks for any info on this!

0
bash nfs stat subshell process-substitution
source share
2 answers

Use Command-Subsitation, Not Process Substitution

Instead of reading from process substitution, use command substitution instead. For example:

 mountpoint=$(stat -t "/my/mountpoint" 2>&1) 

This will disable output by storing standard output in a variable, but leave the results available by playing out $ mountpoint. This approach also leaves available exit status through $ ?.

Simpler alternative

Alternatively, you can simply rewrite this more simply:

 mountpoint="/my/mountpoint" if stat -t "$mountpoint" 2>&- then echo "NFS mount stale. Removing..." umount -f -l "$mountpoint" fi 

It seems to me that this seems more attractive and less error prone, but your mileage can certainly vary.

(Ab) using read timeouts

In the comments, the OP asked a question about whether reading timeouts can be abused to process tagged data from stat. The answer is yes, if you close the standard error and check the empty string $ REPLY. For example:

 mountpoint="/my/mountpoint" read -t1 < <(stat -t "$mountpoint" 2>&-) if [[ -n "$REPLY" ]]; then echo "NFS mount stale. Removing..." umount -f -l "$mountpoint" fi 

This works for several reasons:

  • When using inline reading in Bash:

    If no NAMES are supplied, the reading of the string is stored in the REPLY variable.

  • If the standard error is closed, $ REPLY will be empty if stat does not return something to standard output, which will not happen if it encounters an error. In other words, you check the contents of the string $ REPLY instead of the exit status of the read.
+3
source share

I think I get it! The redirection mentioned in your answer seems to work inside the subshell without wiping the return code, like 2> and 1. Thus, this works as expected:

 read -t1 < <(rpcinfo -t 10.0.128.1 nfs 2>&-) if [ $? -eq 0 ]; then echo "NFS server/service available!" else echo "NFS server/service unavailable!" fi 

Where 10.0.128.1 is a "bad" IP (no server / service response). the script expires in a second and creates a "NFS server / service is unavailable!" response, but not inferred from rpcinfo. Similarly, when IP is good, the desired response is displayed.

I supported your answer!

0
source share

All Articles