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.

2
  • 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. Commented Apr 3, 2020 at 2:18
  • Closely related (but assumes the answer to this question as a premise): get last element in bash array Commented Apr 3, 2020 at 2:21

1 Answer 1

2

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

echo "${array[$((${#array[@]} - 1))]}"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.