如何实现Safari下载文件时自动执行自定义脚本修复文件名?
解决Safari非ASCII文件名下载损坏及自动触发脚本方案
一、优先方案:监听Safari下载完成事件(无额外依赖)
利用Safari原生AppleScript接口,精准监听下载完成事件,触发文件名修复脚本,全程无用户交互。
- 编写AppleScript监听脚本(保存为
safari-download-monitor.scpt):
on run -- 后台持续监听Safari下载状态 repeat tell application "Safari" repeat with dl in downloads if (finished of dl) is true and (exists file (path of dl)) then set filePath to path of dl -- 调用bash修复脚本 do shell script "/path/to/your-filename-fixer.sh " & quoted form of filePath -- 标记为已处理,避免重复触发 set finished of dl to false end if end repeat end tell delay 2 -- 每隔2秒检查一次 end repeat end run
- 编写bash文件名修复脚本(保存为
your-filename-fixer.sh):
#!/bin/bash FILE="$1" # 针对Safari非ASCII文件名乱码问题,转换编码修复 mv -v "$FILE" "$(echo "$FILE" | iconv -f UTF-8-MAC -t UTF-8)"
注:若乱码类型不同,可调整编码参数,比如替换为-f ISO-8859-1 -t UTF-8
- 设置后台自动运行:
将AppleScript导出为「应用程序」(勾选「仅运行」),添加到「系统设置-通用-登录项」,开机自动后台启动,无任何交互。
二、备选方案:监控~/Downloads目录(兼容全场景)
若Safari监听方案失效,用fswatch(需通过Homebrew安装:brew install fswatch)监控下载目录新增文件:
- 编写目录监控脚本(保存为
downloads-monitor.sh):
#!/bin/bash DOWNLOAD_DIR="$HOME/Downloads" # 监控目录,仅处理已完成的非临时文件 fswatch -o "$DOWNLOAD_DIR" | while read -r event; do find "$DOWNLOAD_DIR" -type f ! -name "*.part" -mtime -10s | while read -r file; do # 跳过已处理文件 if [ ! -f "$file.processed" ]; then /path/to/your-filename-fixer.sh "$file" touch "$file.processed" # 标记已处理 fi done done
- 设置launchd后台守护:
创建plist配置文件(~/Library/LaunchAgents/com.your.download-monitor.plist):
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>com.your.download-monitor</string> <key>ProgramArguments</key> <array> <string>/bin/bash</string> <string>/path/to/downloads-monitor.sh</string> </array> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> <key>StandardErrorPath</key> <string>/tmp/download-monitor.err</string> <key>StandardOutPath</key> <string>/tmp/download-monitor.out</string> </dict> </plist>
加载并启动服务:
launchctl load ~/Library/LaunchAgents/com.your.download-monitor.plist launchctl start com.your.download-monitor
关键注意事项
- 给脚本添加执行权限:
chmod +x /path/to/your-filename-fixer.sh /path/to/downloads-monitor.sh - 先手动测试修复脚本,确认编码转换逻辑适配你的乱码场景
- 两种方案均需避免重复处理,已通过标记状态实现
内容的提问来源于stack exchange,提问作者Sig
相关产品推荐
相关产品推荐

