You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AppleScript在Terminal中按顺序执行命令(同窗口、前序完成再执行)

解决AppleScript在Terminal中顺序执行命令的问题

你的问题出在两个核心点:默认情况下do script每次调用都会新建Terminal窗口,且不会等待前一个命令执行完成就发送下一个命令。以下是具体修正方案:

核心修改思路

  1. 指定同一窗口执行:所有命令都发送到Terminal的同一个标签页,避免新建窗口。
  2. 等待命令执行完成:通过轮询Terminal标签页的busy状态,确保前一个命令执行完毕后再发送下一个。

修正后的代码

tell application "Terminal"
    -- 确保Terminal窗口存在并激活
    if not (exists window 1) then reopen
    activate
    delay 1 -- 短延迟确保窗口初始化完成

    -- 锁定目标标签页(后续所有命令都在此执行)
    set targetTab to tab 1 of window 1

    -- 执行磁盘格式化命令
    do script "yes | sudo /opt/homebrew/Cellar/e2fsprogs/1.47.0/sbin/mkfs.ext2 -I 128 -L " & nomdisque & " " & diskPath & "s1" in targetTab
    -- 等待命令执行完成
    repeat while busy of targetTab
        delay 1
    end repeat

    -- 执行磁盘挂载命令
    do script "diskutil mountDisk " & diskPath in targetTab
    repeat while busy of targetTab
        delay 1
    end repeat

    -- 在AppleScript内获取挂载点(无需在Terminal执行)
    delay 1 -- 确保挂载操作完全完成
    set mountpoint to do shell script "df -l | grep " & quoted form of diskPath & " | awk '{print $9}'"

    -- 再次挂载磁盘(按需保留)
    do script "diskutil mountDisk " & diskPath in targetTab
    repeat while busy of targetTab
        delay 1
    end repeat

    -- 修改磁盘写入权限
    do script "sudo chmod -R +w " & quoted form of diskPath in targetTab
    repeat while busy of targetTab
        delay 1
    end repeat

    -- 执行rsync同步
    do script "sudo rsync -avP " & sourceFolder & " " & mountpoint in targetTab
    repeat while busy of targetTab
        delay 1
    end repeat

    -- 取消磁盘写入权限
    do script "sudo chmod -R -w " & mountpoint in targetTab
end tell

可选优化:合并连续命令

如果某些命令不需要单独等待(或只需依赖前一个命令成功执行),可以用&&将它们合并成一个do script调用,减少重复的等待代码:

tell application "Terminal"
    if not (exists window 1) then reopen
    activate
    delay 1

    set targetTab to tab 1 of window 1

    -- 合并格式化+挂载命令,&&表示前一个成功才执行下一个
    do script "yes | sudo /opt/homebrew/Cellar/e2fsprogs/1.47.0/sbin/mkfs.ext2 -I 128 -L " & nomdisque & " " & diskPath & "s1 && diskutil mountDisk " & diskPath in targetTab
    repeat while busy of targetTab
        delay 1
    end repeat

    delay 1
    set mountpoint to do shell script "df -l | grep " & quoted form of diskPath & " | awk '{print $9}'"

    -- 挂载+改权限+同步+取消权限合并执行
    do script "diskutil mountDisk " & diskPath & " && sudo chmod -R +w " & quoted form of diskPath & " && sudo rsync -avP " & sourceFolder & " " & mountpoint & " && sudo chmod -R -w " & mountpoint in targetTab
end tell

关键说明

  • in targetTab:强制命令在指定标签页执行,彻底解决多窗口问题。
  • repeat while busy of targetTab:循环检查标签页是否处于忙碌状态,确保命令串行执行。
  • &&与;的区别:&&仅当前一个命令执行成功(返回值为0)时才执行下一个;;则不管前一个命令结果如何,都会执行后续命令,可根据需求替换。

内容的提问来源于stack exchange,提问作者Robin Erard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 07:53:14