Trouble escaping quotes in a shell script

3k views Asked by At

I have a bash script I am making that generates some numbers assignes them to variables then uses osascript to write them out in any application of choice.

Here is a simplified version of what I want to do.

monday1=5
osascript -e 'tell application "System Events" to keystroke "$monday1"'; \

The osascript should look like this

osascript -e 'tell application "System Events" to keystroke "5"'; \

This will then type out the number 5 in what ever app I have my cursor in. The problem is it outputs $monday1 instead. I know I have to do something to escape the quotes so the script can input the variable, but I'm not sure how.

Thoughts?

3

There are 3 answers

1
Jonathan Leffler On BEST ANSWER

The problem is that inside single quotes, there are no special metacharacters, so $monday1 is passed to osascript unchanged. So, you have to make sure that $monday1 is not inside single quotes.

Your options include:

monday1=5
osascript -e 'tell application "System Events" to keystroke "'$monday1'"'

monday1=5
osascript -e 'tell application "System Events" to keystroke "'"$monday1"'"'

monday1=5
osascript -e "tell application \"System Events\" to keystroke \"$monday1\""

monday1=5
osascript -e "tell application 'System Events' to keystroke '$monday1'"

The first stops the single-quoting just after the double quote to surround the key stroke, embeds the value of $monday, and resumes the single-quoting for the remaining double quote. This works because there are no spaces etc in $monday1.

The second is similar to the first but surrounds "$monday1" in double quotes, so it will work even if $monday1 contained spaces.

The third surrounds the whole argument with double quotes, and escapes each embedded double quote. If you're not allergic to backslashes, this is good.

The fourth may or may not work — it depends on whether the osascript program is sensitive to the type of the quotes surrounding its arguments. It simply reverses the use of double quotes and single quotes. (This works as far as the shell is concerned. Gordon Davisson observes in a comment that osascript requires double quotes and does not accept single quotes, so it doesn't work because of the rules of the invoked program — osascript.)

In both the third and fourth cases, you need to be careful if there are other parts of the string that need to be protected so that the shell does not expand the information. In general, single quotes are better, so I'd use one of the first two options.

1
ThisSuitIsBlackNot On

Wrapping your entire string in single quotes prevents the variable monday1 from being interpolated. Switch your double and single quotes:

osascript -e "tell application 'System Events' to keystroke '$monday1'";
0
mvw On

The single quotes form a scope without variable substitution.

osascript -e "tell application \"System Events\" to keystroke \"$monday1\""; \