Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String literal with bash and applescript

This is based on the answer to:

https://apple.stackexchange.com/questions/103565/bash-script-that-will-start-up-second-terminal-process

Doing this applescript command works fine in terminal (it opens a new window and tells me the uptime):

osascript -e 'tell app "Terminal" to do script "uptime"'

However, trying to pass a variable as a string literal does not work:

cmd="'tell app \"Terminal\" to do script \"uptime\"'"
osascript -e ${cmd}

"0:1: syntax error: A unknown token can’t go here. (-2740)"

What's going on?

like image 331
Kevin Kostlan Avatar asked Mar 19 '15 21:03

Kevin Kostlan


2 Answers

I can't really explain why the below works, but it definetively has something to do with parsing text in the shell. The quotes around $cmd, sees to that the space is preserved. Osa script in itself, isn't too happy about apostrophes, (singleticks), so I guess that is why the your version didn't work.

You can do like this:

 cmd="tell application \"Terminal\" to do script \"uptime\""
 osascript -e "$cmd"

At least this worked for me. :)

like image 117
McUsr Avatar answered Oct 17 '22 22:10

McUsr


Similar issue with stopping teamviewer via osascript solved for me by double-escaping in order to get the internal double-quotes. I did not use single quotes to allow bash expansion.

# TeamViewer
alias tvstop="sudo osascript -e \"quit app \\\"TeamViewer.app\\\"\""
alias tvstart="open -g -a /Applications/TeamViewer.app"
like image 1
splaisan Avatar answered Oct 17 '22 21:10

splaisan