Q. How can I print last element in an Bash Array in Linux/Unix?

This is bit tricky question, because we are not sure what could be number of elements in array. By conventional methods we can not find the last element in array. Before learning this trick you should know what is an array and how to use them in shell scripting. For this check our last post on Arrays here and you can even check string manipulation here.

Suppose I have a below given array called ARR1

ARR1=(var1 asdf 123 234 2345)

To print last element in array you can use below commands.

echo ${ARR1[${#ARR1[@]}-1]}
echo ${ARR1[@]:(-1)}

Let me explain what actually above examples mean.

This ${#ARR1[@]} will give what is the size of an array, which will give you 5, but the array base values start from 0, so we have to subtract one from this value which can give you 4. The equation will be changed to $ARR1[4], which is actually 5th and last element in an array.

Second example is straight forward one which will print last element. for understanding : you should know string manipulation.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.