Monday, February 25, 2013

Linux/Unix Shell scripting:Print last array element

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]}
or
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.

0 comments:

Post a Comment