macOS下Automator脚本排除指定包及sudo运行配置求助
解决方案:修正文件夹修改时间脚本的排除逻辑 + Automator sudo配置
一、修正fixFoldersDateMod脚本的排除逻辑
替换原脚本为以下内容,新增精准的包排除判断,避免误修改VST插件、App包等类型的文件:
#!/bin/bash # 定义需排除的macOS包扩展名 EXCLUDED_EXTENSIONS="vst|vst3|app|component|aaxplugin|dpm" # 判断路径是否为需排除的包 is_excluded() { local path="$1" # 匹配扩展名后,验证是否为macOS官方识别的包(bundle) if [[ "$path" =~ \.($EXCLUDED_EXTENSIONS)$ ]]; then if mdls -name kMDItemContentTypeTree -raw "$path" 2>/dev/null | grep -q "com.apple.bundle"; then return 0 fi fi return 1 } # 递归修正文件夹修改时间 fix_folder_date() { local folder="$1" # 跳过排除的包 if is_excluded "$folder"; then echo "跳过排除包: $folder" return fi # 先递归处理子文件夹 for sub_item in "$folder"/*; do [ -d "$sub_item" ] && fix_folder_date "$sub_item" done # 查找当前文件夹及子目录内,非排除包的最新修改文件 local latest_file=$(find "$folder" -type f -exec sh -c '! is_excluded "$0"' {} \; | sort -r -k 6,7 | head -n 1) if [ -n "$latest_file" ]; then # 获取并转换时间格式 local latest_time=$(stat -f "%Sm" -t "%Y%m%d%H%M.%S" "$latest_file") # 更新文件夹修改时间 touch -t "$latest_time" "$folder" echo "已更新: $folder -> $latest_time" else echo "无有效文件,跳过: $folder" fi } # 处理传入的所有文件夹路径 for path in "$@"; do [ -d "$path" ] && fix_folder_date "$path" || echo "无效路径,跳过: $path" done
执行以下命令给脚本添加可执行权限:
chmod +x $HOME/fixFoldersDateMod
二、配置Automator服务以sudo运行
- 打开Automator,新建服务类型文档
- 设置服务接收选定的文件夹,位于Finder.app
- 添加「运行Shell脚本」动作,设置Shell为
/bin/bash,传递输入为作为自变量 - 替换脚本内容为:
# 获取选中的文件夹路径 target_folders="$@" # 弹出系统原生密码对话框 password=$(osascript -e 'tell application "System Events" to display dialog "请输入管理员密码:" default answer "" with hidden answer with title "需要管理员权限" buttons {"取消", "确定"} default button 2' -e 'text returned of result') # 用户取消则退出 [ -z "$password" ] && echo "操作取消" && exit 1 # 用sudo执行修复脚本 echo "$password" | sudo -S "$HOME/fixFoldersDateMod" $target_folders # 执行完成提示(可选) osascript -e 'display notification "文件夹时间修复完成" with title "完成"'
- 保存服务,命名为「修复文件夹修改时间」
关键说明
- 用
mdls判断包类型而非仅匹配扩展名,避免误判普通文件 - 递归处理时优先跳过排除包,确保子目录内的插件包也不被修改
- Automator中通过
osascript调用系统密码对话框,替代终端输入,更符合GUI操作习惯
内容的提问来源于stack exchange,提问作者Max Well
相关产品推荐
相关产品推荐

