如何使用osascript打开iTerm2并运行脚本?解决替换报错问题
解决方案
替换成以下bash脚本即可实现用iTerm2执行指定命令:
#!/bin/bash # 在iTerm2新窗口中运行build:watch osascript -e 'tell application "iTerm2" create window with default profile tell current session of current window write text "cd '"$PWD"' && npm run build:watch" end tell end tell' # 在iTerm2当前窗口新建标签运行firebase模拟器 osascript -e 'tell application "iTerm2" tell current window create tab with default profile tell current session of current tab write text "cd '"$PWD"' && firebase emulators:start --inspect-functions" end tell end tell end tell'
原因说明
iTerm2的AppleScript接口和Terminal语法不同,它没有do script这类直接指令,需要通过以下逻辑实现命令执行:
- 用
create window with default profile创建新窗口(或create tab创建新标签) - 定位到当前窗口/标签的会话对象(
current session) - 通过
write text向会话发送要执行的命令字符串
脚本中'"$PWD"'的写法是为了在AppleScript代码中插入bash的$PWD变量:用单引号包裹整个AppleScript代码段,再通过双引号嵌入bash变量,避免转义冲突。
如果希望两个命令都在独立窗口运行,把第二个osascript片段里的create tab改成create window即可。
内容的提问来源于stack exchange,提问作者Owenn
相关产品推荐
相关产品推荐

