In my script, one of the function returns an array value and I wanted to get its last value and 'cd' into that directory

function name is 'folders' which returns an array holding the values say - 4.5.0 6.0 2.3.1

If I use- cd $(folders[-1]) , I'm facing the following error - my_script.sh: line 350: folders[-1]: command not found

On using - cd ${folders[-1]} , I'm getting - my_script.sh: line 350: folders: bad array subscript

What am I missing here, thanks

1 Answers

2
Shawn On

${foo[-1]} works on my ksh. But if it doesn't for you, maybe:

#!/bin/ksh93
foo=(1 2 3)
echo "${foo[-1]}" # Should print 3
echo "${foo[${#foo[@]} - 1]}" # Should also print 3

${#foo[@]} returns the number of elements in the array variable, so you just subtract one from that to get the last element.