Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 250
Bernd Avatar asked May 28 '14 22:05

Bernd


People also ask

How do I declare a variable in bash?

There are no data types. A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.

How do I declare a string variable in bash?

To initialize a string, you directly start with the name of the variable followed by the assignment operator(=) and the actual value of the string enclosed in single or double quotes. Output: This simple example initializes a string and prints the value using the “$” operator.

Does bash have variable scope?

Variable Scope of Bash Functions Scope refers to the visibility of variables. By default, every variable has a global scope that means it is visible everywhere in the script. You can also create a variable as a local variable.


1 Answers

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 !

like image 51
Idriss Neumann Avatar answered Sep 19 '22 14:09

Idriss Neumann