Mac后台Shell脚本监控根目录文件夹:等待命名后打开谷歌表格故障排查
问题修复:Mac后台脚本监测文件夹重命名失效的解决办法
问题背景
需要在Mac后台运行Shell脚本,实现以下功能:
- 监测指定卷的根目录(
/Volumes/KLP-Working) - 当根目录新建文件夹时,等待用户完成文件夹命名(不再是“untitled folder”/“Untitled Folder”)
- 命名完成后自动打开指定Google Sheets链接
当前脚本故障:添加等待命名逻辑后,始终判定文件夹处于未命名状态,无法触发打开链接的操作。
故障原因分析
原脚本的wait_for_naming函数存在两个核心问题:
- 错误的
find命令逻辑:find "$parent_dir" -maxdepth 1 -type d -name "$original_folder_name" -o -name "*"会匹配父目录下所有目录,导致current_folder_path始终返回第一个匹配的目录(大概率还是初始的未命名文件夹),无法正确获取重命名后的路径。 - 跟踪的是旧路径而非实际文件夹:文件夹重命名后,初始的
$event路径(比如/Volumes/KLP-Working/untitled folder)会失效,但脚本仍在基于旧名称查找,自然无法识别重命名后的状态。
修复方案
修改wait_for_naming函数,通过inode跟踪文件夹(重命名不会改变文件的inode),循环检查父目录下inode匹配的目录,获取当前名称:
修复后的完整脚本
#!/bin/bash # Directory to watch WATCHED_DIR="/Volumes/KLP-Working" # Google Sheets URL GOOGLE_SHEET_URL="http://www.urlgoeshere.com" # Function to open URL in Google Chrome open_google_sheet() { osascript -e "tell application \"Google Chrome\" to open location \"$GOOGLE_SHEET_URL\"" } # Function to check if the folder has been named wait_for_naming() { # 获取目标文件夹的inode(重命名不会改变inode) target_inode=$(stat -f "%i" "$1") parent_dir=$(dirname "$1") while true; do # 在父目录中查找inode匹配的目录 current_folder_path=$(find "$parent_dir" -maxdepth 1 -type d -inum "$target_inode" -print -quit) if [ -z "$current_folder_path" ]; then echo "Folder no longer exists. Exiting..." break fi current_folder_name=$(basename "$current_folder_path") # 检查是否已完成命名 if [[ "$current_folder_name" != "untitled folder" && "$current_folder_name" != "Untitled Folder" ]]; then echo "Folder named: $current_folder_name" open_google_sheet break else echo "Waiting for folder to be named..." fi sleep 2 done } # Function to check if the watched directory exists check_and_monitor() { while true; do if [ -d "$WATCHED_DIR" ]; then echo "Monitoring $WATCHED_DIR for new folders..." fswatch -0 --event Created "$WATCHED_DIR" | while read -d "" event do # 检查是否为根目录下的文件夹 relative_path="${event#"$WATCHED_DIR/"}" if [[ "$relative_path" != */* && -d "$event" ]]; then echo "New folder detected: $event" wait_for_naming "$event" fi done else echo "Waiting for $WATCHED_DIR to be available..." sleep 10 fi done } # Start monitoring when the directory is available check_and_monitor
关键修改点
- 用inode跟踪文件夹:通过
stat -f "%i" "$1"获取文件夹的inode,重命名后inode保持不变,确保能持续追踪到同一个文件夹。 - 修正
find命令:find "$parent_dir" -maxdepth 1 -type d -inum "$target_inode" -print -quit精准查找inode匹配的目录,避免匹配无关目录。 - 简化条件判断:合并目录检查和层级判断的逻辑,让代码更简洁。
使用说明
- 确保已安装
fswatch:如果未安装,可通过Homebrew安装:brew install fswatch - 给脚本添加执行权限:
chmod +x your_script_name.sh - 后台运行脚本:
nohup ./your_script_name.sh &
内容的提问来源于stack exchange,提问作者Cory Wonderly
相关产品推荐
相关产品推荐

