问题描述
我在 Bash 中使用 osascript
通过 Apple Script 在通知中心 (Mac OS X) 中显示消息.我正在尝试将文本变量从 Bash 传递给脚本.对于没有空格的变量,这很好用,但不适用于有空格的变量:
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:
定义
var1="Hello"
var2="Hello World"
和使用
osascript -e 'display notification "'$var1'"'
有效,但使用
osascript -e 'display notification "'$var2'"'
收益
syntax error: Expected string but found end of script.
我需要改变什么(我是新手)?谢谢!
What do I need to change (I am new to this)? Thanks!
推荐答案
你可以尝试改用 :
osascript -e "display notification \"$var2\""
或者:
osascript -e 'display notification "'"$var2"'"'
这解决了在 bash 中操作包含空格的变量的问题.但是,此解决方案不能防止注入 osascript 代码.因此,最好选择 Charles Duffy 的解决方案 之一或使用 bash
参数扩展:
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//\"/}"'"'
感谢 mklement0 这个非常有用的建议!
Thank to mklement0 for this very useful suggestion !
这篇关于osascript 使用带空格的 bash 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!