osascript 使用带空格的 bash 变量 [英] osascript using bash variable with a space

查看:26
本文介绍了osascript 使用带空格的 bash 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆