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

6ie5vjzr  于 6个月前  发布在  Shell
关注(0)|答案(3)|浏览(91)

我正在尝试运行存储在变量osascript中的两个命令
我的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)

mfuanj7w

mfuanj7w1#

@Barmar:执行脚本的参数需要用双引号括起来。
是的,但是,你这样做仍然不安全。
如果路径本身包含反斜杠或双引号,AS将抛出语法错误,因为编译的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代码中任何引用错误的可能性更小。

neskvpey

neskvpey2#

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

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

字符串
您还应该将cd的参数放在引号中,以防它包含空格。

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

ecfdbz9o

ecfdbz9o3#

下面是为我工作的。
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

相关问题