【问题标题】:How to compare two stat values of the same file?如何比较同一文件的两个统计值?
【发布时间】:2018-02-16 05:01:58
【问题描述】:

Screenshot of the my code

我正在尝试制作一个 shell 程序,它可以告诉我文件何时创建、何时修改以及何时删除。我想我可以解决这个问题,但我唯一的问题是我无法比较统计值。它告诉我我有“太多的争论”。任何帮助将不胜感激:)

#!/bin/bash

run=yes

if [ -f $1 ]
then

    while [ run=yes ]
    do

        time1=$(stat -c %y $1)

        time2=$(stat -c %y $1)

        if [ ! $time2 ]
        then
            echo "The file "$1" has been deleted."
            run=no

        elif [ $time2 -gt $time1 ]
        then
            echo "The file "$1" has been modified."
            run=no
fi
done

else
    while [ run=yes ]
    do
    sleep 2

        if [ -f $1 ]
        then
        echo "The file "$1" has been created."
        run=no
fi
done
fi

【问题讨论】:

  • 使用bash -n yourscript 来测试语法错误。在此处发布 bash 问题之前,您可能还需要考虑通过 shellcheck.net 运行您的脚本。有助于确保您发布的挑战实际上会受益于人类的关注。很多事情可以立即检测和修复,无需等待社区的答复。

标签: linux shell unix terminal


【解决方案1】:

代码现在可以运行,如果有人想知道,我想我会分享最终结果。

#!/bin/bash

run=true

if [ -f $1 ]
then

while [ "$run" = true ]
do

    time1=$(stat -c %Y $1 2>/dev/null)
    sleep $2
    time2=$(stat -c %Y $1 2>/dev/null)

    if [ ! "$time2" ]
    then
        echo "The file "$1" has been deleted."
        run=false

    elif [ $time2 -gt $time1 ]
    then
        echo "The file "$1" has been modified."
        run=false
fi

else
while [ "$run" = true ]
do
sleep 2

    if [ -f $1 ]
    then
    echo "The file "$1" has been created."
    run=false
fi
done
fi

【讨论】:

  • 这仍然有很多错误可以在shellcheck.net 快速检测到。试一试。你会喜欢的。 :)
【解决方案2】:

static -c %y ... 的输出包含空格,这是 shell 用来分隔参数的。然后运行时:

if [ ! $time2 ]; then

这翻译成这样的:

if [ ! 2017-09-02 08:57:19.449051182 -0400 ]; then

这是一个错误。 ! 运算符只需要一个参数。你可以用引号解决它:

if [ ! "$time2" ]; then

或者通过使用特定于 bash 的 [[...]]] 条件:

if [[ ! $time2 ]]; then

(有关第二种解决方案的详细信息,请参阅 bash(1) 手册页)。

另外,您无法将时间与-gt 进行比较,如下所示:

    elif [ $time2 -gt $time1 ]

这(a)与之前的if语句有同样的问题,并且(b)-gt只能用于比较整数,不能用于时间字符串。

如果您使用%Y 而不是%y,您将获得自纪元以来的整数秒数,这将解决上述所有问题。

【讨论】:

  • 非常感谢!这真的很有帮助!我现在可以成功打印消息了。但是,脚本应该在打印消息后停止运行。在我的情况下,脚本继续运行。可能是因为 run 变量有问题?
猜你喜欢
  • 2020-12-29
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 2019-06-19
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多