17

osascript在 Bash 中使用通过 Apple Script 在通知中心 (Mac OS X) 中显示消息。我正在尝试将文本变量从 Bash 传递给脚本。对于没有空格的变量,这很好用,但不适用于带有空格的变量:

定义

var1="Hello"
var2="Hello World"

并使用

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

有效,但使用

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

产量

syntax error: Expected string but found end of script.

我需要改变什么(我是新手)?谢谢!

4

2 回答 2

31

您可以尝试改用:

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

或者 :

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

这解决了在 bash 中操作包含空格的变量的问题。但是,此解决方案不能防止 osascript 代码的注入。因此,最好选择Charles Duffy 的解决方案之一或使用bash参数扩展:

# 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 这个非常有用的建议!

于 2014-05-28T22:47:22.243 回答
18

与尝试使用字符串连接的变体不同,此版本对注入攻击是完全安全的。

osascript \
  -e "on run(argv)" \
  -e "return display notification item 1 of argv" \
  -e "end" \
  -- "$var2"

...或者,如果有人更喜欢在标准输入而不是 argv 上传递代码:

osascript -- - "$var2" <<'EOF'
  on run(argv)
    return display notification item 1 of argv
  end
EOF
于 2014-05-28T22:53:41.117 回答