osascript 使用带空格的 bash 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23923017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:33:41  来源:igfitidea点击:

osascript using bash variable with a space

bashvariablessyntaxapplescriptosascript

提问by Bernd

I am using osascriptin 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:

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

Defining

定义

var1="Hello"
var2="Hello World"

and using

并使用

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

works, but using

有效,但使用

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

yields

产量

syntax error: Expected string but found end of script.

What do I need to change (I am new to this)? Thanks!

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

回答by Idriss Neumann

You could try to use instead :

您可以尝试改用:

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

Or :

或者 :

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

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 solutionsor to use bashparameter expansion :

这解决了在 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//\"/}"'"'

Thank to mklement0 for this very useful suggestion !

感谢 mklement0 这个非常有用的建议!

回答by Charles Duffy

This version is completely safe against injection attacks, unlike variants trying to use string concatenation.

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

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

...or, if one preferred to pass code in on stdin rather than argv:

...或者,如果人们更喜欢在 stdin 而不是 argv 上传递代码:

osascript -- - "$var2" <<'EOF'
  on run(argv)
    return display notification item 1 of argv
  end
EOF