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

I fiddled around trying to extract one quoted word from a string in zsh and the obvious things to try didn't work, e.g .:

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

      

When I tried this first on the command line, I was prompted to continue the line with braceparam quote>

, followed by another single quote, and then again with braceparam>

, after which I was followed by another closing parenthesis. Much to my surprise, this actually gave the correct index. All together, this is what works to get the index of the first single quote in a string $foo

:

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

      

Good thing I found something that works, but can anyone explain why it works?

Edited to add a complete example:

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

      

+1


source to share


1 answer


Edit as chepner pointed out:

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

      


First, ̶ this is how I think you should make replacements, like this: ̶

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 do not think that this is by design, but the syntax check does not interpret the passage as a wildcard, but as a quotation, which should be completed.



Oddly enough, the parser correctly interprets your replacement when you add an extra } .

Although he actually ignores it. You can actually try:

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

      

And surprisingly, it works.

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

If you put a double quote above the substitution, the syntax check won't complain and work correctly. I think you should add them because the form you suggested (no double quotes) is not documented and the behavior may change in future versions of zsh.

+2


source







All Articles