LuisEnMarroquin
LuisEnMarroquin

Reputation: 1919

Run 2 commands in applescript/osascript with variable

I am trying to run 2 commands stored in a variable with osascript

This is my start.sh

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

echo $currentDirectory

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

I am getting this as the output

sh start.sh
cd /Users/Picadillo/Movies/my-test-tepo && npm run start
83:84: syntax error: Expected expression but found “&”. (-2741)

Upvotes: 0

Views: 615

Answers (3)

Myunghoon Haru Lee
Myunghoon Haru Lee

Reputation: 71

Below is what worked for me.

pathToRepo is the variable, which osascript passed to a Terminal that was open and it cd into the correct directory. (And then run npm start which is just for reference if you wanted to add more commands)

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

Source/Reference: https://stackoverflow.com/a/67413043/6217734

Upvotes: 0

has
has

Reputation: 176

@Barmar: The argument to do script needs to be in double quotes.

Yes; however, the way you’ve done it is still unsafe.

If the path itself contains backslashes or double quotes, AS will throw a syntax error as the munged AS code string fails to compile. (One might even construct a malicious file path to execute arbitrary AS.) While these are not characters that frequently appear in file paths, best safe than sorry. Quoting string literals correctly is always a nightmare; correctly quoting them all the way through shell and AppleScript quadratically so.

Fortunately, there is an easy way to do it:

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

Pass the currentDirectory path as an additional argument to osascript (the - separates any options flags from extra args) and osascript will pass the extra argument strings as parameters to the AppleScript’s run handler. To single-quote that AppleScript string to pass back to shell, simply get its quoted form property.

Bonus: scripts written this way are cleaner and easier to read too, so less chance of overlooking any quoting bugs you have in your shell code.

Upvotes: 2

Barmar
Barmar

Reputation: 780974

The argument to do script needs to be in double quotes.

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

You should also put the argument to cd in quotes, in case it contains spaces.

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

Upvotes: 2

Related Questions