我正在使用Bash中的osascript通过苹果脚本在通知中心(Mac )显示一条消息。我正在尝试将一个文本变量从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.我需要改变什么(我是新手)?谢谢!
发布于 2014-05-29 06:47:22
您可以尝试使用以下命令:
osascript -e "display notification \"$var2\""或者:
osascript -e 'display notification "'"$var2"'"'这修复了在bash中操作包含空格的变量的问题。然而,这种解决方案并不能防止osascript代码的注入。因此,最好选择Charles Duffy's solutions之一或使用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-29 06:53:41
与尝试使用字符串连接的变体不同,此版本是完全安全的,不会受到注入攻击。
osascript \
-e "on run(argv)" \
-e "return display notification item 1 of argv" \
-e "end" \
-- "$var2"...or,如果你更喜欢在标准输入而不是argv上传递代码:
osascript -- - "$var2" <<'EOF'
on run(argv)
return display notification item 1 of argv
end
EOFhttps://stackoverflow.com/questions/23923017
复制相似问题