Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

osascript using bash variable with a space

I am using osascript in Bash to display a message in Notification Center (Mac OS X) via Apple Script. I am trying to pass a text variable from Bash to the script. For a variable without spaces, this works just fine, but not for one with spaces:

Defining

var1="Hello"
var2="Hello World"

and using

osascript -e 'display notification "'$var1'"'

works, but using

osascript -e 'display notification "'$var2'"'

yields

syntax error: Expected string but found end of script.

What do I need to change (I am new to this)? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try to use instead :

osascript -e "display notification "$var2""

Or :

osascript -e 'display notification "'"$var2"'"'

This fixes the problem of manipulation of variables that contains spaces in bash. However, this solution doesn't protect against injections of osascript code. So it would be better to choose one of Charles Duffy's solutions or to use bash parameter expansion :

# if you prefer escape the doubles quotes
osascript -e "display notification "${var2//"/"}""
# or
osascript -e 'display notification "'"${var2//"/"}"'"'

# if you prefer to remove the doubles quotes
osascript -e "display notification "${var2//"/}""
# or
osascript -e 'display notification "'"${var2//"/}"'"'

Thank to mklement0 for this very useful suggestion !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...