更改多个文件夹的修改日期以匹配其最近修改的文件的

时间:2017-07-22 08:53:22

标签: bash shell applescript

我一直在使用以下shell bin / bash脚本作为应用程序,我可以删除文件夹,它将更新文件夹的修改日期以匹配该文件夹中最近修改的文件。

for f in each "$@"
do
    echo "$f"
done
$HOME/setMod "$@"

这将获取文件夹名称,然后将其传递到我的主文件夹中的此setMod脚本。

#!/bin/bash
# Check that exactly one parameter has been specified - the directory
if [ $# -eq 1 ]; then
   # Go to that directory or give up and die
   cd "$1" || exit 1
   # Get name of newest file
   newest=$(stat -f "%m:%N" * | sort -rn | head -1 | cut -f2 -d:)
   # Set modification date of folder to match
   touch -r "$newest" .
fi

但是,如果我一次删除多个文件夹,它将无效,我无法弄清楚如何让它同时使用多个文件夹。

另外,我从Apple支持部门那里了解到,我的文件夹中有很多文件不断更新的原因是由于与Time Machine相关的一些过程,尽管事实上我多年没有触及其中的一些。如果有人知道防止这种情况发生的方法,或以某种方式自动定期更新文件夹修改日期以匹配其中最近修改过的文件的日期/时间,这将使我免于必须运行此步骤手动定期。

1 个答案:

答案 0 :(得分:1)

setMod脚本当前只接受一个参数。 你可以让它接受许多参数并循环它们, 或者你可以让调用脚本使用循环。

我采用第二种选择,因为调用者脚本有一些错误和弱点。在此,它会根据您的目的进行更正和扩展:

for dir; do
    echo "$dir"
    "$HOME"/setMod "$dir"
done

或者让setMod接受多个参数:

#!/bin/bash

setMod() {
   cd "$1" || return 1
   # Get name of newest file
   newest=$(stat -f "%m:%N" * | sort -rn | head -1 | cut -f2 -d:)
   # Set modification date of folder to match
   touch -r "$newest" .
}

for dir; do
   if [ ! -d "$dir" ]; then
       echo not a directory, skipping: $dir
       continue
   fi

   (setMod "$dir")
done

注意:

  • for dir; do相当于for dir in "$@"; do
  • (setMod "$dir")周围的括号使其在子shell中运行,因此脚本本身不会更改工作目录,cd操作的效果仅限于子shell在(...)
相关问题