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.
Latest posts by Surendra Anne (see all)
- Docker: How to copy files to/from docker container - June 30, 2020
- Anisble: ERROR! unexpected parameter type in action:
Fix - June 29, 2020 - FREE: JOIN OUR DEVOPS TELEGRAM GROUPS - August 2, 2019
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018