0

I had to create a bash array on Mac OS as follows. The $1 represents # of git commits you want to store in the array.

IFS=$'\n' read -rd '' -a array<<< "$(git log -n $1 | grep commit |  awk '{print $2}')"

I can't access last array item as ${array[-1]}. I get the error "array: bad array subscript".

However, when I create the array on linux OS, I can access the last array item in the same way successfully.

readarray -t array <<< "$(git log -n $1 | grep commit |  awk '{print $2}')"

echo ${array[-1]} is successful on Linux machine but not on Mac OS machine.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 2
    Apple ships bash 3.2; this is ancient -- current releases are in the 5.x series. You have the option to install a newer one with Nix, MacPorts, Homebrew, etc. – Charles Duffy Apr 03 '20 at 02:18
  • Closely related (but assumes the answer to this question as a premise): [get last element in bash array](https://stackoverflow.com/questions/36977855/get-last-element-in-bash-array) – Charles Duffy Apr 03 '20 at 02:21

1 Answers1

2

In a bash too old to support negative subscripts, you end up needing to do something like:

echo "${array[$((${#array[@]} - 1))]}"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441