How to get last element of array?

I found an  issue explaining how to access element of array by index. Can reverse indexes be used as well, or is there any way to access last element? 

run: echo '${{github.event.commits[-1].message}}'

returns empty string even through when

run: echo '${{ toJson(github) }}'

is called, there is a text in the message of last commit

Hi @noxor ,

To get the github context element, please check the json body firstly and follow the structure for your code. For instance, my ‘on: push’ event github context as below:


commits body has only one element which highlighted with {}, you can get the message from ${{ github.event.commits[0].message }}.

And there’s a ‘head_commit’ element, you can get the head commit(last) message from 

${{ github.event.head_commit.message }} as well.

If the body has mutliple elements like below array structure(fake just for example), you can use {{ github.event.commits[0].message }} for message 1, and {{ github.event.commits[1].message }}  for message 2.

"commits": [
        "message": "this is message 1"
        "message2": "this is message 2"

Hope it’s clear and helpful!

1 Like

Thanks for reply,

the ‘head_commit’ seems to solve my problem, since I needed to read message of merge commit to release branch. It was not possible to use normal indexes, because number of elements in ‘commits’ can vary.