Skip to content

自动化

本章将介绍 macOS 自动化工具,包括 Automator、快捷指令、AppleScript 和 Shell 脚本等内容。

自动化概述

macOS 自动化工具

text
macOS 自动化工具:

快捷指令 (Shortcuts)
├── 图形化工作流创建
├── 跨设备同步
├── Siri 语音触发
└── macOS Monterey 及以后

Automator
├── 创建自动化工作流
├── 应用程序、服务、文件夹操作
├── 支持 AppleScript 和 Shell 脚本
└── 所有 macOS 版本

AppleScript
├── 应用程序自动化
├── 自然语言语法
├── GUI 脚本
└── 与应用程序深度集成

Shell 脚本
├── 系统级自动化
├── 强大的文本处理
├── 定时任务
└── 命令行工具集成

launchd
├── 系统服务管理
├── 定时任务
├── 事件触发
└── 后台进程

快捷指令

创建快捷指令

text
打开快捷指令:
- 应用程序 → 快捷指令
- 或 Spotlight 搜索 "快捷指令"

创建快捷指令:
1. 点击 "+" 创建新快捷指令
2. 添加操作
3. 配置参数
4. 测试运行
5. 命名并保存

常用操作类型:
├── 脚本
├── 文件
├── 网络
├── 文本
├── 媒体
└── 共享

常用快捷指令示例

text
示例一:快速清理下载文件夹
操作:
1. 获取下载文件夹内容
2. 筛选文件(按日期或类型)
3. 删除文件

示例二:批量调整图片大小
操作:
1. 选择照片
2. 调整图片大小
3. 保存到指定位置

示例三:发送每日报告
操作:
1. 获取日历事件
2. 格式化文本
3. 发送邮件

命令行调用快捷指令

bash
# 列出所有快捷指令
shortcuts list

# 运行快捷指令
shortcuts run "快捷指令名称"

# 查看快捷指令详情
shortcuts view "快捷指令名称"

# 从命令行创建快捷指令
# 需要在快捷指令应用中创建

Automator

Automator 简介

bash
# 打开 Automator
open -a Automator

# Automator 工作流类型:
# - 应用程序:独立运行的应用
# - 服务:系统服务菜单
# - 文件夹操作:监控文件夹变化
# - 打印插件:打印时触发
# - 图像捕捉插件:导入图片时触发
# - 日历闹钟:日历事件触发

创建工作流

text
创建 Automator 工作流:

1. 选择工作流类型
2. 从资源库拖拽操作
3. 配置操作参数
4. 测试工作流
5. 保存

常用操作:
├── 文件和文件夹
│   ├── 获取指定的访达项目
│   ├── 复制访达项目
│   ├── 移动访达项目
│   └── 重命名访达项目
├── 文本
│   ├── 获取文本内容
│   ├── 更改文本大小写
│   └── 替换文本
├── 照片和图像
│   ├── 调整图像大小
│   ├── 旋转图像
│   └── 转换图像格式
└── 实用工具
    ├── 运行 AppleScript
    ├── 运行 Shell 脚本
    └── 显示通知

实用工作流示例

text
示例一:批量重命名文件
1. 获取指定的访达项目
2. 给访达项目重命名
   - 序列和日期
   - 添加文本
   - 替换文本

示例二:图片批量处理
1. 获取指定的访达项目
2. 过滤访达项目(仅图片)
3. 调整图像大小
4. 保存到指定文件夹

示例三:定时备份
1. 获取指定的访达项目
2. 创建归档
3. 移动到备份位置

AppleScript

AppleScript 基础

applescript
-- AppleScript 基本语法

-- 显示对话框
display dialog "Hello, World!"

-- 带按钮的对话框
display dialog "确认操作?" buttons {"取消", "确定"} default button "确定"

-- 获取用户输入
set userName to text returned of (display dialog "请输入姓名:" default answer "")

-- 显示通知
display notification "操作完成" with title "通知"

-- 播放提示音
beep

控制流程

applescript
-- 条件判断
set score to 85

if score >= 90 then
    display dialog "优秀"
else if score >= 80 then
    display dialog "良好"
else if score >= 60 then
    display dialog "及格"
else
    display dialog "不及格"
end if

-- 循环
repeat 5 times
    display dialog "循环"
end repeat

-- 带计数器的循环
repeat with i from 1 to 10
    display dialog "第 " & i & " 次"
end repeat

-- 遍历列表
set fruits to {"苹果", "香蕉", "橙子"}
repeat with fruit in fruits
    display dialog fruit
end repeat

-- while 循环
set count to 0
repeat while count < 5
    set count to count + 1
    display dialog "计数: " & count
end repeat

Finder 操作

applescript
-- Finder 自动化

-- 获取当前文件夹
tell application "Finder"
    set currentFolder to folder of front window
    display dialog name of currentFolder
end tell

-- 创建文件夹
tell application "Finder"
    make new folder at desktop with properties {name:"新文件夹"}
end tell

-- 移动文件
tell application "Finder"
    move file "文件名" of desktop to folder "Documents" of home
end tell

-- 复制文件
tell application "Finder"
    duplicate file "文件名" of desktop
end tell

-- 重命名文件
tell application "Finder"
    set name of file "旧名称.txt" of desktop to "新名称.txt"
end tell

-- 获取文件列表
tell application "Finder"
    set fileList to name of every file of desktop
    display dialog fileList as text
end tell

应用程序控制

applescript
-- 控制 Safari
tell application "Safari"
    activate
    open location "https://www.baidu.com"
    delay 2
    set pageContent to source of document 1
end tell

-- 控制 Mail
tell application "Mail"
    set newMessage to make new outgoing message with properties {subject:"主题", content:"正文"}
    tell newMessage
        make new to recipient at end of to recipients with properties {address:"email@example.com"}
    end tell
    send newMessage
end tell

-- 控制日历
tell application "Calendar"
    make new event at end of events of calendar "工作" with properties {summary:"会议", start date:(current date), end date:(current date) + 3600}
end tell

-- 控制音乐
tell application "Music"
    play
    pause
    next track
    previous track
end tell

运行 Shell 脚本

applescript
-- 在 AppleScript 中运行 Shell 命令
do shell script "ls -la"

-- 获取命令输出
set fileList to do shell script "ls ~/Desktop"

-- 使用变量
set userName to "张三"
do shell script "echo 'Hello, " & userName & "'"

-- 执行需要权限的命令
do shell script "sudo command" with administrator privileges

Shell 脚本自动化

定时任务

bash
# 使用 launchd 创建定时任务

# 创建 plist 文件
# ~/Library/LaunchAgents/com.user.dailytask.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.user.dailytask</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/bash</string>
        <string>/Users/用户名/scripts/daily_task.sh</string>
    </array>
    <key>StartCalendarInterval</key>
    <dict>
        <key>Hour</key>
        <integer>9</integer>
        <key>Minute</key>
        <integer>0</integer>
    </dict>
    <key>StandardOutPath</key>
    <string>/tmp/dailytask.log</string>
    <key>StandardErrorPath</key>
    <string>/tmp/dailytask_error.log</string>
</dict>
</plist>

# 加载任务
launchctl load ~/Library/LaunchAgents/com.user.dailytask.plist

# 卸载任务
launchctl unload ~/Library/LaunchAgents/com.user.dailytask.plist

# 查看任务状态
launchctl list | grep dailytask

文件夹监控

bash
# 创建文件夹操作工作流

# 使用 fswatch(需安装)
brew install fswatch

# 监控文件夹变化
fswatch -o ~/Downloads | while read; do
    echo "文件夹有变化: $(date)"
done

# 自动处理新文件
fswatch ~/Downloads | while read file; do
    echo "新文件: $file"
    # 处理文件
done

系统维护脚本

bash
#!/bin/bash
# 系统维护脚本

# 清理缓存
echo "清理系统缓存..."
rm -rf ~/Library/Caches/*

# 清理日志
echo "清理旧日志..."
find ~/Library/Logs -mtime +30 -delete

# 清理下载文件夹
echo "清理下载文件夹中的旧文件..."
find ~/Downloads -mtime +30 -delete

# 清理废纸篓
echo "清空废纸篓..."
rm -rf ~/.Trash/*

# 更新 Homebrew
echo "更新 Homebrew..."
brew update
brew upgrade
brew cleanup

# 检查磁盘空间
echo "磁盘空间:"
df -h /

# 检查内存使用
echo "内存使用:"
vm_stat

echo "维护完成!"

实用自动化示例

自动备份脚本

bash
#!/bin/bash
# 自动备份脚本

# 配置
SOURCE_DIR="$HOME/Documents"
BACKUP_DIR="/Volumes/Backup"
DATE=$(date +%Y%m%d)
BACKUP_NAME="backup_$DATE"

# 创建备份目录
mkdir -p "$BACKUP_DIR/$BACKUP_NAME"

# 同步文件
rsync -av --delete "$SOURCE_DIR/" "$BACKUP_DIR/$BACKUP_NAME/"

# 创建压缩包
tar -czf "$BACKUP_DIR/${BACKUP_NAME}.tar.gz" -C "$BACKUP_DIR" "$BACKUP_NAME"

# 删除临时目录
rm -rf "$BACKUP_DIR/$BACKUP_NAME"

# 删除旧备份(保留最近 7 个)
cd "$BACKUP_DIR"
ls -t backup_*.tar.gz | tail -n +8 | xargs rm -f

echo "备份完成: ${BACKUP_NAME}.tar.gz"

截图自动处理

bash
#!/bin/bash
# 截图自动处理脚本

# 监控截图文件夹
SCREENSHOT_DIR="$HOME/Desktop"
OUTPUT_DIR="$HOME/Pictures/Screenshots"

mkdir -p "$OUTPUT_DIR"

# 使用 fswatch 监控
fswatch "$SCREENSHOT_DIR" | while read file; do
    if [[ "$file" == *"截图"* ]] || [[ "$file" == *"Screenshot"* ]]; then
        # 移动文件
        mv "$file" "$OUTPUT_DIR/"
        echo "截图已移动: $(basename "$file")"
    fi
done

网络状态监控

bash
#!/bin/bash
# 网络状态监控脚本

LOG_FILE="$HOME/network_monitor.log"

while true; do
    # 检查网络连接
    if ping -c 1 8.8.8.8 > /dev/null 2>&1; then
        STATUS="在线"
    else
        STATUS="离线"
    fi
    
    # 记录状态
    echo "$(date): $STATUS" >> "$LOG_FILE"
    
    # 离线时发送通知
    if [ "$STATUS" = "离线" ]; then
        osascript -e 'display notification "网络连接已断开" with title "网络监控"'
    fi
    
    # 每 60 秒检查一次
    sleep 60
done

自动整理下载文件

bash
#!/bin/bash
# 自动整理下载文件

DOWNLOADS="$HOME/Downloads"

# 按扩展名分类
declare -A categories=(
    ["图片"]="jpg jpeg png gif bmp svg"
    ["文档"]="pdf doc docx xls xlsx ppt pptx txt rtf"
    ["压缩包"]="zip rar 7z tar gz"
    ["音乐"]="mp3 wav flac aac m4a"
    ["视频"]="mp4 avi mkv mov wmv"
    ["代码"]="py js html css java cpp c h"
)

# 遍历下载文件夹
for file in "$DOWNLOADS"/*; do
    if [ -f "$file" ]; then
        # 获取扩展名
        ext="${file##*.}"
        ext="${ext,,}"  # 转小写
        
        # 查找分类
        for category in "${!categories[@]}"; do
            if [[ " ${categories[$category]} " =~ " $ext " ]]; then
                # 创建目标文件夹
                target_dir="$DOWNLOADS/$category"
                mkdir -p "$target_dir"
                
                # 移动文件
                mv "$file" "$target_dir/"
                echo "已移动: $(basename "$file") -> $category/"
                break
            fi
        done
    fi
done

echo "整理完成!"

小结

本章介绍了 macOS 自动化的主要内容:

  1. 自动化工具:了解各种自动化工具的特点
  2. 快捷指令:创建和使用快捷指令
  3. Automator:创建自动化工作流
  4. AppleScript:应用程序自动化脚本
  5. Shell 脚本:系统级自动化
  6. 定时任务:使用 launchd 创建定时任务
  7. 实用示例:备份、监控、整理等自动化脚本

通过自动化,可以大大提高工作效率,减少重复性工作。建议根据自己的需求,创建适合的自动化工作流。