Getting the Last Element in a Bash Array

Posted on Nov. 22, 2012, 5:43 p.m.

Every so often, my colleagues and I find ourselves stretching Bash to the limits of what it's supposed to do. Often, something like Perl or Python would be better choices for the task at hand. But for a variety of reasons, using those languages is not an option. This post will show you how to take a path like /home/silviogutierrez/www/example.com and get just example.com.

For those of you thinking that basename will do the same thing: while true, that only works for directories and for the last part of the path. The technique shown here lets you explode around periods, hyphens, underscores, etc. It also lets you get other elements besides the last one by using the offsets -2, -3, and so on.

Learning Bash? Subscribe to my Bash articles, tips and tutorials.

First, let's set our variable:

1
THE_LONG_PATH=/home/silviogutierrez/www/example.com

Then, let's split up the PATH into an array of directories:

1
2
# Syntax //DELIMITER//. We use \/ because we need to escape the delimiter.    
DIRS=(${THE_LONG_PATH//\// })

And finally, let's get the last element. To do this, we first get the length of the array, using the # notation, and then subtract one. To get a length of an
array we just do:

1
2
3
LENGTH=${#DIRS[@]} # Get the length.                                          
LAST_POSITION=$((LENGTH - 1)) # Subtract 1 from the length.                   
LAST_PART=${DIRS[${LAST_POSITION}]} # Get the last position.

We can just combine these steps into the shorter version - if harder to read:

1
LAST_PART=${DIRS[${#DIRS[@]} - 1]}

And that's it, LAST_PART should now contain example.com. Hope that helps.
Here's the full version all in one piece:

1
2
3
THE_LONG_PATH=/home/silviogutierrez/www/example.com                           
DIRS=(${THE_LONG_PATH//\// })                                                 
LAST_PART=${DIRS[${#DIRS[@]} - 1]}
Tags: shell Bash