使用变量在 applescript/osascript 中运行 2 个命令

问题描述 投票:0回答:3

我正在尝试使用

osascript

运行存储在变量中的 2 个命令

这是我的

start.sh

currentDirectory="cd $(pwd) && npm run start"

echo $currentDirectory

osascript -e 'tell application "Terminal" to do script '"${currentDirectory}"''

我将其作为输出

sh start.sh
cd /Users/Picadillo/Movies/my-test-tepo && npm run start
83:84: syntax error: Expected expression but found “&”. (-2741)
bash shell applescript sh osascript
3个回答
2
投票

@Barmar:执行脚本的参数需要用双引号引起来。

是的;然而,你这样做的方式仍然不安全。

如果路径本身包含反斜杠或双引号,AS 将抛出语法错误,因为 munged AS 代码字符串无法编译。 (人们甚至可能构建恶意文件路径来执行任意 AS。)虽然这些不是文件路径中经常出现的字符,但最好还是安全一点。正确引用字符串文字始终是一场噩梦;通过 shell AppleScript 二次正确地引用它们。

幸运的是,有一个简单的方法可以做到:

currentDirectory="$(pwd)"

osascript - "${currentDirectory}" <<EOF 
on run {currentDirectory}
  tell application "Terminal"
    do script "cd " & (quoted form of currentDirectory) & " && npm run start"
  end tell
end run
EOF

currentDirectory
路径作为附加 参数 传递给
osascript
-
将任何选项标志与额外参数分开),并且
osascript
将额外的参数字符串作为参数传递给 AppleScript 的
run handler
。要将 AppleScript 字符串单引号传递回 shell,只需获取其
quoted form
属性即可。

奖励:以这种方式编写的脚本也更干净、更容易阅读,因此忽略 shell 代码中任何引用错误的机会更小。


2
投票

do script
的参数需要用双引号引起来。

osascript -e 'tell application "Terminal" to do script "'"${currentDirectory}"'"'

您还应该将

cd
的参数放在引号中,以防它包含空格。

currentDirectory="cd '$(pwd)' && npm run start"

0
投票

以下是对我有用的。

pathToRepo
是变量,
osascript
传递到打开的终端,然后
cd
进入正确的目录。 (然后运行
npm start
,如果您想添加更多命令,仅供参考)

pathToRepo="/Users/<YOUR_MAC_NAME>/Documents/<REPO_NAME>"

osascript - "$pathToRepo" <<EOF
    on run argv -- argv is a list of strings
        tell application "Terminal"
            do script ("cd " & quoted form of item 1 of argv & " && npm start")
        end tell
    end run
EOF

来源/参考:https://stackoverflow.com/a/67413043/6217734

© www.soinside.com 2019 - 2024. All rights reserved.