繁体   English   中英

如何检查文件是否已创建/删除/更改(Bash)

[英]How to check if a file is created/deleted/changed (Bash)

declare -i fil="$1"
declare -t tid="$2"
notFinished=true
finnes=false

if [ -f $fil ];
then
finnes = true
fi

while $notFinished;
do

if [ -f $fil && ! $finnes ];          (14)
then
echo "Filen: $fil ble opprettet."
finished=true
fi

if [ ! -f $fil && $finnes ];         (20)
then
echo "Filen: $fil ble slettet."
finished=true
fi

sleep $tid
done

我正在尝试检查是否在脚本有效期内创建或删除了名称为$ fil的文件,仅每隔$ tid秒检查一次。 我还想通过比较时间戳来检查文件是否被更改,但是我不太确定该怎么做。.我只是想提一下,这是第一次尝试使用这种语言进行编程。

我现在遇到的唯一错误是:

  /home/user/bin/filkontroll.sh: line 14: [: missing `] '
  /home/user/bin/filkontroll.sh: line 20: [: missing `] '

@edit:固定notFinished和一些间距

您可以使用如下形式:

#!/bin/bash

declare -i fil="$1"
declare -t tid="$2"
notFinished=true
finnes=false

if [ -f "$fil" ]; then
   finnes=true
fi

while [ "$notFinished" = true ];
do
    if [ -f "$fil" ] && [ ! "$finnes" = true ]; then
       echo "Filen: $fil ble opprettet."
       finished=true
    fi

    if [ ! -f "$fil" ] && [ "$finnes" = true ]; then
       echo "Filen: $fil ble slettet."
       finished=true
    fi

    sleep $tid
done

注意,您应该阅读如何在Shell脚本中声明和使用布尔变量? 有趣的问题和答案(链接到我更喜欢的答案),以便您可以看到布尔检查应该这样进行(这不仅适用于if ,还适用于while ):

if [ "$bool" = true ]; then

另外,请注意我引用了变量。 这是一个好习惯,可以避免在未设置变量的情况下有时因奇怪的行为而发疯。

me@box:/tmp $ if [ a ] ; then echo foo; fi foo me@box:/tmp $ if [ b ] ; then echo foo; fi foo me@box:/tmp $ if [ a && b ] ; then echo foo; fi bash: [: missing `]' me@box:/tmp $ if [ a ] && [ b ] ; then echo foo; fi foo me@box:/tmp $ if [[ a && b ]] ; then echo foo; fi foo

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM