编写Bash函数通过osascript复用Shell命令时遇语法错误求助
修复Bash+AppleScript调用的语法错误
问题根源
- Bash变量赋值错误:
local command = "$1"中等号两边有空格,Bash不允许赋值语句的等号前后存在空格,导致变量未正确初始化。 - AppleScript字符串语法冲突:直接将包含双引号的Shell命令传入AppleScript时,未转义内部双引号,破坏了AppleScript的字符串结构,引发语法错误。
修复后的代码
execute_commands() { # 修复赋值语句的空格问题 local command="$1" # 转义命令中的双引号,适配AppleScript字符串格式 local escaped_command="${command//\"/\\\"}" osascript <<EOF tell application "iTerm" tell last session of current tab of current window write text "$escaped_command" end tell end tell EOF } # 函数调用(无需手动转义&,直接用&&即可) execute_commands "cd \"$PROJECT_PATH\"/frontend && npm run dev"
关键修复点
- 去掉
local赋值语句中等号两边的空格,保证Bash正确解析变量赋值。 - 使用Bash参数扩展
${command//\"/\\\"}将命令中的所有双引号替换为\",避免AppleScript将内部双引号识别为字符串结束标记。 - 将AppleScript的
write text参数用双引号包裹,明确标记完整字符串范围。
内容的提问来源于stack exchange,提问作者Oleg Kipling
相关产品推荐
相关产品推荐

