Sandesh Veerapur
Sandesh Veerapur

Reputation: 51

How to access last item in bash array on Mac OS?

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.

Upvotes: 0

Views: 542

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295443

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

echo "${array[$((${#array[@]} - 1))]}"

Upvotes: 2

Related Questions