如何将通过AppleScript按键操作在Terminal中执行命令的输出保存到AppleScript变量或Bash变量?
问题分析
你遇到的核心问题是:keystroke命令只是模拟用户按键操作,它不会返回Terminal中命令的输出结果,所以直接把keystroke return赋值给变量arrow_result是无效的,这就是为什么会提示变量未定义的错误。
模拟按键的方式更适合自动化用户交互流程,但不适合捕获命令输出——因为Terminal的输出是显示在窗口界面中,AppleScript无法直接通过keystroke获取这些内容。下面提供两种更可靠的解决方案:
方案1:在AppleScript中直接执行命令并捕获输出
如果你不需要看到Terminal窗口的交互过程,只是想获取命令执行结果,可以用AppleScript的do shell script命令直接执行Shell命令,它会返回命令的输出内容:
#!/bin/bash osascript <<EOF -- 直接执行Shell命令并捕获结果 set commandResult to do shell script "cd /Users/uwe/documents/coding/c/pshell && make compile_and_run && bash tests/user_test.sh" -- 显示结果 display dialog commandResult with title "命令执行结果" EOF
注意点:
do shell script是在后台执行命令,不会打开Terminal窗口;如果需要同时打开Terminal窗口并执行命令,可以结合tell application "Terminal"来操作:
这种方式需要在系统偏好设置的「安全性与隐私」中给Terminal和脚本启用辅助功能权限,否则无法读取窗口内容。tell application "Terminal" activate -- 在Terminal中执行命令 do script "cd /Users/uwe/documents/coding/c/pshell && make compile_and_run && bash tests/user_test.sh" in front window -- 等待命令执行完成(根据实际情况调整延迟时间) delay 3 -- 获取Terminal窗口的内容(需要启用辅助功能) set windowContent to contents of front window display dialog windowContent end tell
方案2:将结果保存到Bash变量中
你提到的“将结果存储到Bash变量中”是完全可以实现的,甚至不需要依赖AppleScript的模拟按键。直接在Bash中执行命令并捕获输出,再根据需要用AppleScript处理:
#!/bin/bash # 执行命令并将输出保存到Bash变量 shell_result=$(cd /Users/uwe/documents/coding/c/pshell && make compile_and_run && bash tests/user_test.sh) # 可选:如果需要在Terminal中实时看到输出,同时保存到变量,可以用tee # shell_result=$(cd /Users/uwe/documents/coding/c/pshell && make compile_and_run && bash tests/user_test.sh | tee /dev/tty) # 用AppleScript显示结果 osascript <<EOF display dialog "$shell_result" with title "Bash捕获的结果" EOF # 或者直接在Bash中输出结果 echo "命令执行结果:" echo "$shell_result"
总结
避免用模拟按键的方式捕获命令输出,这种方式不仅不可靠,还容易因为延迟时间设置不当导致执行失败。优先选择直接执行命令并捕获输出的方案,无论是在AppleScript还是Bash中都能更稳定地获取结果。
内容的提问来源于stack exchange,提问作者Phil
相关产品推荐
相关产品推荐

