bash命令“ read -r”有时会失败

时间:2019-11-13 01:47:56

标签: bash

我有一个小的脚本来读取文件系统的可用性,以检查文件系统中剩余了多少空间,该脚本有时可以工作,但是由于未知原因而失败。当它失败时,它将永远无法恢复。我看不出是什么原因导致无法使用。欣赏是否有人可以深入了解问题。

while :; do
    str="$(df  | grep '/var/log' )"
    if [ $? -ne 0 ]; then
            echo "Somethin's wrong"
    fi
    if [ -z "$str" ]; then
            echo null str
            sleep 1
            continue
    fi
    read -r map size used avail use mount <<< $str
    if [ -z "$avail" ]; then
        echo Iter:$ext: mount: $mount avail:$avail size:$size, use:$use, used:$used
    fi
    if [ $avail -eq 0 ]; then
        echo Iter:$ext: mount: $mount avail:$avail size:$size, use:$use, used:$used
        break
    else
        sleep 1
    fi
done

失败日志:

+ :
++ grep /var/log
++ df
+ str='/dev/mapper/vg--db--sda-dat.log.1           495844   138915    331329  30% /var/log'
+ '[' 0 -ne 0 ']'
+ '[' -z '/dev/mapper/vg--db--sda-dat.log.1           495844   138915    331329  30% /var/log' ']'
+ read -r map size used avail use mount
+ '[' -z '' ']'
+ echo Iter:6: mount: avail: size:, use:, used:
Iter:6: mount: avail: size:, use:, used:
+ '[' -eq 0 ']'
./run.sh: line 83: [: -eq: unary operator expected
+ sleep 1
+ :
++ df
++ grep /var/log
+ str='/dev/mapper/vg--db--sda-dat.log.1           495844   138916    331328  30% /var/log'
+ '[' 0 -ne 0 ']'
+ '[' -z '/dev/mapper/vg--db--sda-dat.log.1           495844   138916    331328  30% /var/log' ']'
+ read -r map size used avail use mount
+ '[' -z '' ']'
+ echo Iter:6: mount: avail: size:, use:, used:
Iter:6: mount: avail: size:, use:, used:
+ '[' -eq 0 ']'
./run.sh: line 83: [: -eq: unary operator expected
+ sleep 1
+ :

1 个答案:

答案 0 :(得分:1)

您正确测试

if [ -z "$avail" ]; then

但是即使$ avail为空,您仍然执行

if [ $avail -eq 0 ]; then

这将导致错误消息。放入

if [ -z "$avail" ]; then
...
elif [ $avail -eq 0 ]; then
...
fi