Why does this parameter expansion for finding the index of a single quote in a string work?

∥☆過路亽.° 提交于 2019-12-11 07:48:07

问题


I was messing around trying to extract a single quoted word from a string in zsh, and the obvious things to try didn't work, like these:

${foo[(i)']}
${foo[(i)'']}
${foo[(i)\']}

When I tried that first one on the command line, it prompted me to continue the line with braceparam quote>, which I followed with another single quote, then again with braceparam>, which I followed with another closing brace. Much to my surprise, this actually gave the correct index. All joined together, this is what works to get the index of the first single quote in a string $foo:

${foo[(i)']}'}

It's nice that I found something that works, but can anyone explain why it works?

Edited to add full example:

foo="a 'bar' -l"
echo ${foo[(i)']}'}                        # echoes "3"
echo ${foo[${foo[(i)']}'},${foo[(I)']}'}]} # echoes "'bar'"

回答1:


Edit as pointed out by chepner:

since (i) takes a pattern, ${foo[(i)[\']]} should and does work as expected.

F̶i̶r̶s̶t̶ ̶o̶f̶ ̶a̶l̶l̶,̶ ̶t̶h̶i̶s̶ ̶i̶s̶ ̶h̶o̶w̶ ̶I̶ ̶t̶h̶i̶n̶k̶ ̶y̶o̶u̶ ̶s̶h̶o̶u̶l̶d̶ ̶d̶o̶ ̶t̶h̶e̶ ̶s̶u̶b̶s̶t̶i̶t̶u̶t̶i̶o̶n̶ ̶l̶i̶k̶e̶ ̶t̶h̶i̶s̶:̶

echo "${foo[(i)']}"
#or
echo "$foo[(i)']"

N̶o̶w̶,̶ ̶i̶t̶ ̶s̶e̶e̶m̶s̶ ̶t̶o̶ ̶m̶e̶ ̶t̶h̶a̶t̶ ̶y̶o̶u̶ ̶f̶o̶u̶n̶d̶ ̶e̶i̶t̶h̶e̶r̶ ̶a̶ ̶b̶u̶g̶ ̶o̶r̶ ̶a̶ ̶q̶u̶i̶r̶k̶ ̶o̶f̶ ̶z̶s̶h̶.̶ I don't think this is done by design, but the syntax checker is not intepreting the quote as a single character of the substitution, but as a quote to be completed.

Weirdly enough the parser is interpreting correctly your substitution when you put an extra }'.

Although it is actually ignoring it. You can actually try:

echo ${foo[(i)']}HiMomImOnTV'}

And surprisingly it works as well.

Maybe you should open a bug report, or ask the developer mailing list.

If you put the double quote over the substitution the syntax checker doesn't complain and it works correctly. I think you should add them, because the form you suggested (without double quotes), is not documented, and the behaviour might change in future versions of zsh.



来源:https://stackoverflow.com/questions/25778521/why-does-this-parameter-expansion-for-finding-the-index-of-a-single-quote-in-a-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!