Getting the Last Element in a Bash Array

Posted on 2012-11-22 22:43:02+00:00

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

Comments

Liam Condron-Farnos2013-07-30 22:46:42+00:00

In this particular case, you could also just:

long_path=/home/silviogutierrez/www/example.com last_part=${long_path##*/}

IIRC, this will also work with POSIX /bin/sh, whereas arrays are a bashism.

Reply
silviogutierrez2013-08-04 22:46:41+00:00

Good to know, thanks!

Reply
Manos Johan Hanssen Seferidis2014-08-28 14:47:35+00:00

You can also use sed: echo "/home/silviogutierrez/www/example.com" | sed 's/.*\///'

Reply
SedParameterSeparator2014-09-10 17:06:39+00:00

In this case, you should use another parameter separator for sed for readability: echo "/home/silviogutierrez/www/example.com" | sed 's|.*/||'

Reply
petch2014-10-15 08:39:15+00:00

Read from http://code.linuxnix.com/2013/02/linuxunix-shell-scriptingprint-last-array-element.html, LAST_PART=${DIRS[@]:(-1)}

Reply
rizz2pro .2015-08-24 16:59:57+00:00

The text on this page made my eyes bleed and now I am blind. Where am i?

Reply

Post New Comment