In Bash, I can use the ${parameter:offset:length}
notation to slice elements of an array, but I can't use it in all the same ways as I would when slicing a string. Specifically, I would like to use this syntax to print all but the last n
elements of an array:
note: --version
output is metasyntax, not the intent of my question
calvin@rose:~ A=($(bash --version |head -1)); echo ${A[@]}
GNU bash, version 4.4.12(1)-release (x86_64-pc-linux-gnu)
calvin@rose:~ echo ${A[3]:0:-8} # Negative length of substring
4.4.12(1)
calvin@rose:~ echo ${A[@]:2:2} # Predictable behavior with [@]
version 4.4.12(1)-release # Desired output
calvin@rose:~ echo ${A[@]:2:-1} # Desired input
-bash: -1: substring expression < 0 # Limitation of Bash Arrays?
This behavior is defined under Parameter Expansion:
If parameter is ‘@’, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero.
There are two workarounds I currently use:
calvin@rose:~ unset A[-1]; echo ${A[@]:2} # This works, but I lose data
version 4.4.12(1)-release
calvin@rose:~ echo ${A[@]:2: ${#A[@]}-3 } # This works, but it gets messy fast
version 4.4.12(1)-release
Is there a better way? The python A[2:-1]
kids are making fun of me.