Nick Chambers
2017-10-04 20:02:23 UTC
Hello all! I am using bash4.4 and have some questions about slices in bash. For my first example:
NickChambers-iMac:~ Nick$ str='this is a message'
NickChambers-iMac:~ Nick$ echo "${str:4:(-1)}"
is a messag
NickChambers-iMac:~ Nick$
This clearly allows a negative index, but if I try to do the same thing with an array, I get the following:
NickChambers-iMac:~ Nick$ colors=(purple blue orange yellow green)
NickChambers-iMac:~ Nick$ echo "${colors[@]:1:3}" # expected
blue orange yellow
NickChambers-iMac:~ Nick$ echo "${colors[@]:1:(-1)}"
-bash: (-1): substring expression < 0
NickChambers-iMac:~ Nick$
Is there a reason why this can be done on strings but not on arrays?
Also, incidentally, is there a better way to span from an index to the end of the string besides using something like the following:
NickChambers-iMac:~ Nick$ str='this is a message'
NickChambers-iMac:~ Nick$ strlen=${#str}
NickChambers-iMac:~ Nick$ echo "${str:4:strlen}"
is a message
NickChambers-iMac:~ Nick$
NickChambers-iMac:~ Nick$ str='this is a message'
NickChambers-iMac:~ Nick$ echo "${str:4:(-1)}"
is a messag
NickChambers-iMac:~ Nick$
This clearly allows a negative index, but if I try to do the same thing with an array, I get the following:
NickChambers-iMac:~ Nick$ colors=(purple blue orange yellow green)
NickChambers-iMac:~ Nick$ echo "${colors[@]:1:3}" # expected
blue orange yellow
NickChambers-iMac:~ Nick$ echo "${colors[@]:1:(-1)}"
-bash: (-1): substring expression < 0
NickChambers-iMac:~ Nick$
Is there a reason why this can be done on strings but not on arrays?
Also, incidentally, is there a better way to span from an index to the end of the string besides using something like the following:
NickChambers-iMac:~ Nick$ str='this is a message'
NickChambers-iMac:~ Nick$ strlen=${#str}
NickChambers-iMac:~ Nick$ echo "${str:4:strlen}"
is a message
NickChambers-iMac:~ Nick$