我一直在使用以下 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 支持部门了解到,我的许多文件夹不断更新模组日期的原因是由于一些与时间机器相关的过程,尽管事实上我已经很多年没有碰过其中的一些文件夹了。如果有人知道一种方法可以防止这种情况发生,或者以某种方式自动定期更新文件夹的修改日期以匹配其中最近修改的文件的日期/时间,那么我就不必运行此步骤定期手动操作。
最佳答案
当前的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
注释:
代表目录; do
相当于for dir in "$@";做
(setMod "$dir")
两边的括号使其在子 shell 中运行,这样脚本本身就不会更改工作目录,即cd 的效果
操作仅限于(...)
内的子shell
关于bash - 更改多个文件夹的修改日期以匹配其最近修改的文件的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45252626/