Macos 如何在AppleScript中转义shell参数?
Applescript似乎无法正确转义字符串。我做错了什么 例如:Macos 如何在AppleScript中转义shell参数?,macos,escaping,applescript,arguments,Macos,Escaping,Applescript,Arguments,Applescript似乎无法正确转义字符串。我做错了什么 例如: set abc to "funky-!@#'#\"chars" display dialog abc display dialog quoted form of abc 预期/期望输出: funky-!@#'#"chars 'funky-!@#\'#"chars' 实际产量: funky-!@#'#"chars 'funky-!@#'\''#"chars' 如您所见,在实际输出中,Applescript似乎正在添加和转义一
set abc to "funky-!@#'#\"chars"
display dialog abc
display dialog quoted form of abc
预期/期望输出:
funky-!@#'#"chars
'funky-!@#\'#"chars'
实际产量:
funky-!@#'#"chars
'funky-!@#'\''#"chars'
如您所见,在实际输出中,Applescript似乎正在添加和转义一个额外的'
如果结尾字符是“
或”
,我可以接受,单引号和双引号都可以转义,但似乎只有单引号实际转义。使用“引号形式”。通常在applescript中,我们处理的是“mac”“设置路径的样式,这样我们就可以这样将其传递给shell
set theFile to choose file
set dirname to do shell script "dirname " & quoted form of POSIX path of theFile
反斜杠通常不会在shell中的单引号内解释 在单引号中包含字符将保留单引号中每个字符的文字值。单引号不能出现在单引号内 反斜杠不能用于转义在单引号中设置的字符串中的单引号。嵌入的引号可以通过书写来创建,例如:“a'\''b',这将产生a'b 但是,它们由sh中的echo解释,sh是由
do shell脚本使用的shell
:
do shell script "echo " & quoted form of "\\t" --> "\t"
取消设置xpg\u echo
使其行为类似于bash中的echo:
do shell script "shopt -u xpg_echo; echo " & quoted form of "\\t" --> "\\t"
通常,使用herdoc重定向更简单:
do shell script "rev <<< " & quoted form of "a\\tb" --> "b\\ta"
do shell script“revNo,在'funky-!@@\''\'''\''chars'
中没有添加额外的'
正如17510427541297
所指出的,AppleScript的引用形式的
习惯用法是用于Unix shell中的,如果Unix shell中的字符串直接相邻放置,则会连接起来
AppleScript的abc的引号形式就是这样:它创建一个用单引号括起来的字符串,但用\'
替换每个单引号
实际上,这会创建三个单独的字符串,但在(大多数)Unix shell中,这三个单独的字符串受以下字符串浓缩机制的约束:
“funky-!@@@chars”
变成“funky-!@@@chars”
+\
+'.\chars'
结果字符串适合由Unix shell解释为单个文本字符串(而不会导致参数扩展问题等)
我更新了这个问题,因为在测试之后,这似乎不起作用。谢谢你的帮助。Applescript不能很好地使用双引号中的单引号。如果将字符串更改为funky-@#\“#\”字符
工作正常。我会认为这是一个错误,但没有必要屏住呼吸来修复苹果。也许在这里问:,或者我可以问。是的!如果你能问的话,那就太好了。谢谢。它应该像'It'\'s
而不是'It'
@Lri-什么/为什么?对我来说,这似乎没有正确地转义。@cwd尝试在shell中运行say'funky'chars'
。您会收到PS2提示,因为单引号的数量不均匀。
# in Terminal.app
# note the escaping in: osascript -e '...'\''...'
quotedsrt="$(osascript -e '
set abc to "funky-!@#'\''#\"chars"
return quoted form of abc
')"
echo "$quotedsrt" # 'funky-!@#'\''#"chars'
eval echo "$quotedsrt" # funky-!@#'#"chars
echo echo "$quotedsrt" | sh
# escaping mechanism for Bash shell
set +H
esc="'\''"
str="funky-!@#'#\"chars"
str="'${str//\'/${esc}}'"
set -H
echo "$str" # 'funky-!@#'\''#"chars'
eval echo "$str" # funky-!@#'#"chars
echo echo "$str" | sh