【问题标题】:Check file existence every 30 seconds每 30 秒检查一次文件是否存在
【发布时间】:2014-06-10 09:23:44
【问题描述】:

为什么这不起作用?我需要每 30 秒检查一次文件是否存在。

STATUS=0
FILENAME="helloworld.file"
while [ $STATUS -eq "0" ] do
if [ -f $FILENAME ];
    then STATUS=1;
else
    sleep 30s;
fi

done

【问题讨论】:

  • 第 3 行你忘了分号:while [ $STATUS -eq "0" ]; do
  • @Michal Kordas 如果您要解决拼写错误,请在帖子中修复所有内容。这不一定适用于此编辑,但您最近建议的一些编辑在帖子中遗漏了重大问题。
  • @mikeTheLiar,我一定会做更彻底的评论
  • @Michal 干杯,谢谢

标签: bash unix if-statement while-loop terminal


【解决方案1】:

你忘记了; ==>

while [ "$STATUS" -eq "0" ]; do
if [ -f "$FILENAME" ]; then 
    STATUS=1
else
    sleep 30
fi

或者:

while [ "$STATUS" -eq "0" ] 
do
    if [ -f "$FILENAME" ]
    then 
        STATUS=1
    else
        sleep 30
    fi
done

此外,不要忘记使用双引号保护您的变量或使用 [[ 语法。

Here is a reminder about the necessity (or not) to protect your variables with double quotes.

你也可以简化你的代码:

while true; do
    [[ -f $FILENAME ]] && break
    sleep 30
done

【讨论】:

    【解决方案2】:

    不知道,请问shellcheck

    In file line 3:
    while [ $STATUS -eq "0" ] do
                              ^-- SC1010: Use semicolon or linefeed before 'do' (or quote to make it literal).
    

    好的,那我们就这样做吧:

    STATUS=0
    FILENAME="helloworld.file"
    while [ $STATUS -eq "0" ]
    do
    if [ -f $FILENAME ];
        then STATUS=1;
    else
        sleep 30s;
    fi
    
    done
    

    【讨论】:

    • shellcheck:太酷了!在向 SO 发布问题之前,也许这应该是一个要求。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多