gpt4 book ai didi

linux - 如何比较同一文件的两个统计值?

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:42 25 4
gpt4 key购买 nike

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

最佳答案

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,您将获得自纪元以来的整数秒数的时间,这将解决所有问题以上问题。

关于linux - 如何比较同一文件的两个统计值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46096649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com