首页 > 解决方案 > 文件位置的bash数组 - 如何找到最后更新的文件?

问题描述

有一个从我需要循环并找出最新的并打印最新的定位命令构建的文件数组。我们有一个名为 randomname-properties.txt 的属性文件,它位于多个位置,有时称为 randomname-properties.txt.bak 或 randomname-properties.txt.old。示例如下

目录结构

/opt/test/something/randomname-properties.txt
/opt/test2/something/randomname-properties.txt.old
/opt/test3/something/randomname-properties.txt.bak
/opt/test/something1/randomname-properties.txt.working

代码

#Builds list of all files 
PropLoc=(`locate randomname-properties.txt`)
#Parse list and remove older file
for i in ${PropLoc[@]} ; do
  if [ ${PropLoc[0]} -ot ${PropLoc[1]} ] ; then
    echo "Removing ${PropLoc[0]} from the list as it is older"
    #Below should rebuild the array while removing the older element
    PropLoc=( "${PropLoc[@]/$PropLoc[0]}" )
  fi
done
echo "Latest file found is ${PropLoc[@]}"

总的来说,这是行不通的。目前看来,它甚至没有进入循环,因为前两个文件具有与去年相同的时间戳(对于超过一年的事情,似乎在过去的一天没有冲突)。关于如何让它正常工作的任何想法?谢谢

标签: arraysbashloopstimestamp

解决方案


您可以使用ls -t,它将按修改时间对文件进行排序。第一行将是最新的文件。

newest=$(ls -t "${PropLoc[@]}" | head -n 1)

只要没有文件名包含换行符,这应该可以工作。

不要忘记引用您的变量,以防它们包含空格或通配符。


推荐阅读