Shell脚本:检查一个目录中的任何文件是否比另一个目录中的任何文件更新

时间:2017-08-15 14:32:57

标签: shell timestamp

如果一个目录中的文件比另一个目录中的文件更新,我想在shell脚本中运行命令。

我想要这样的东西

if [ dir1/* <have been modified more recently than> dir2/* ]; then
  echo 'We need to do some stuff!'
fi

3 个答案:

答案 0 :(得分:1)

BashFAQ #3中所述,此处细分为可重复使用的函数:

newestFile() {
  local latest file
  for file; do
    [[ $file && $file -nt $latest ]] || latest=$file
  done
}

directoryHasNewerFilesThan() {
  [[ "$(newestFile "$1"/*)" -nt "$(newestFile "$2" "$2"/*)" ]]
}

if directoryHasNewerFilesThan dir1 dir2; then
  echo "We need to do something!"
else
  echo "All is well"
fi

如果要将目录本身计为文件,也可以这样做;只需将"$(newestFile "$1"/*)"替换为"$(newestFile "$1" "$1"/*)",同样替换为newestFile $2的调用。

答案 1 :(得分:1)

使用/ bin / ls

#!/usr/bin/ksh

dir1=$1
dir2=$2

#get modified time of directories
integer dir1latest=$(ls -ltd --time-style=+"%s" ${dir1} | head -n 2 | tail -n 1 | awk '{print $6}')
integer dir2latest=$(ls -ltd --time-style=+"%s" ${dir2} | head -n 2 | tail -n 1 | awk '{print $6}')

#get modified time of the latest file in the directories
integer dir1latestfile=$(ls -lt --time-style=+"%s" ${dir1} | head -n 2 | tail -n 1 | awk '{print $6}')
integer dir2latestfile=$(ls -lt --time-style=+"%s" ${dir2} | head -n 2 | tail -n 1 | awk '{print $6}')

#sort the times numerically and get the highest time
val=$(/bin/echo -e "${dir1latest}\n${dir2latest}\n${dir1latestfile}\n${dir2latestfile}" | sort -n | tail -n 1)

#check to which file the highest time belongs to
case $val in
   @(${dir1latest}|${dir1latestfile})) echo $dir1 is latest ;;
   @(${dir2latest}|${dir2latestfile})) echo $dir2 is latest ;;
esac

答案 2 :(得分:0)

这很简单,以机器格式(纪元时间)获取两个文件夹的时间戳,然后进行简单的比较。这都是

相关问题