Ber*_*rnd 12 variables syntax bash applescript osascript
我osascript在Bash中使用通过Apple Script在通知中心(Mac OS X)中显示消息.我试图将文本变量从Bash传递给脚本.对于没有空格的变量,这可以正常工作,但不适用于带空格的变量:
定义
var1="Hello"
var2="Hello World"
Run Code Online (Sandbox Code Playgroud)
和使用
osascript -e 'display notification "'$var1'"'
Run Code Online (Sandbox Code Playgroud)
工作,但使用
osascript -e 'display notification "'$var2'"'
Run Code Online (Sandbox Code Playgroud)
产量
syntax error: Expected string but found end of script.
Run Code Online (Sandbox Code Playgroud)
我需要改变什么(我是新手)?谢谢!
Idr*_*ann 20
您可以尝试使用:
osascript -e "display notification \"$var2\""
Run Code Online (Sandbox Code Playgroud)
要么 :
osascript -e 'display notification "'"$var2"'"'
Run Code Online (Sandbox Code Playgroud)
这解决了操作包含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//\"/}"'"'
Run Code Online (Sandbox Code Playgroud)
感谢mklement0提供这个非常有用的建议!
Cha*_*ffy 11
与尝试使用字符串连接的变体不同,此版本对注入攻击是完全安全的.
osascript \
-e "on run(argv)" \
-e "return display notification item 1 of argv" \
-e "end" \
-- "$var2"
Run Code Online (Sandbox Code Playgroud)
...或者,如果一个人更喜欢在stdin而不是argv上传递代码:
osascript -- - "$var2" <<'EOF'
on run(argv)
return display notification item 1 of argv
end
EOF
Run Code Online (Sandbox Code Playgroud)