Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Unexpected/Bogus results for string slices



I was wondering whether I could put the two indexes of a string/array slice into a single variable, i.e., whether "str=1234567890; slice=4,6; $str[$slice]" would expand to "456". The answer is no but while trying this out I found a number of unexpected/bogus results.

One issue is that "$str[$slice]" expands to "4" while "$str[slice]" expands to "6".

Another issue seems to be that after an opening square bracket. the parser looks for a comma even within nested contexts like quoted strings or "${…}" expressions.

See the annotated transcript below for concrete examples.

$ slice=4,6
$ echo $((4,6))
6                       OK
$ echo $((slice))
6
                       OK
$ echo $(($slice))
6
                       OK
$ str=1234567890
$ echo $str[$((4,6))]
6
                       OK
$ echo $str[$((slice))]
6
                       OK
$ echo $str[$(($slice))]
6
                       OK
$ echo $str[slice]
6
                       OK
$ echo $str[$slice]
4
                       Why is that not 6?
$ echo $str[2,slice]
23456                   OK
$ echo $str[2,$slice]
234                     Why not 23456?
$ echo $str[slice,8]
678                     OK
$ echo $str[$slice,8]
45678                   Why not 678?
$ echo $str[4\,6]
456                     Shouldn't that be 6 (or 4)?
$ echo $str["4,6"]
456                     This for sure can't be right.
$ echo $str['4,6']
test.zsh:23: bad math _expression_: operand expected at `'4'
123456                  What's wrong here?
$ echo $str[${:-4,6}]
test.zsh:24: closing brace expected
123456                  Braces look balanced to me.
$ echo $str[${:-"4,6"}]
test.zsh:25: parse error
123456                  What's wrong?
$ echo $str[${:-'4,6'}]
test.zsh:26: closing brace expected
123456
                  Braces look balanced to me.
$ echo $str["${:-4,6}"]
test.zsh:28: closing brace expected
123456
                  Braces look balanced to me.
$ echo $str["${:-"4,6"}"]
test.zsh:29: parse error
123456
                  What's wrong?
$ echo $str["${:-'4,6'}"]
test.zsh:30: closing brace expected
123456
                  Braces look balanced to me.
$ echo $str['${:-4,6}']
test.zsh:32: closing brace expected
123456
                  Braces look balanced to me.

Philippe



Messages sorted by: Reverse Date, Date, Thread, Author