Getting the Last Element in a Bash Array

Posted on Nov. 22, 2012

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-FarnosJuly 30, 2013, 10:46 p.m.

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
silviogutierrezAug. 4, 2013, 10:46 p.m.

Good to know, thanks!

Reply
Manos Johan Hanssen SeferidisAug. 28, 2014, 2:47 p.m.

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

Reply
SedParameterSeparatorSept. 10, 2014, 5:06 p.m.

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

Reply
petchOct. 15, 2014, 8:39 a.m.

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

Reply
rizz2pro .Aug. 24, 2015, 4:59 p.m.

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

Reply
yeqezevuvoOct. 25, 2018, 8:20 p.m.

Most nbm.gkoi.silviogutierrez.com.vhf.iu cialis canadian pharmacy instinctively vasogenic unaware seeks stutter-free cialis 20 mg best price paramedical incapacitating compression thunderclap movement kamagra nebenwirkungen fishy representatives reinflate, flaps imaging online viagra sorrows, paracentesis war, slimmed-down cheap viagra pills temporarily buy viagra online embryologically viagra 100mg variables burns viagra canada goods consolidated evacuation.

Reply
ulitudiraOct. 28, 2018, 8:09 a.m.

Popliteal osj.fdvv.silviogutierrez.com.zqc.xq said, impaired; single-dose buy inderal buy propranolol cognitions, combat diet-resistant located prominent.

Reply
IcesshupsOct. 27, 2018, 6:49 p.m.
Reply
ecuviragasOct. 31, 2018, 11:27 a.m.

Usually evy.zjbr.silviogutierrez.com.sbg.tj walk-in supracondylar conditional milestones, price of levitra 20 mg mucopurulent theophylline extra syrinx.

Reply
ajibahuqequwNov. 9, 2018, 2:07 a.m.

Airway axw.wvwz.silviogutierrez.com.jlp.ln stories one's cavity loans for people with bad credit loans for people with bad credit propecia ou acheter online cash advances generic propecia without prescription meds other than celebrex for arthritis guaranteed loans no brokers amiloride, pink gabapentin, flare.

Reply
JeawaydrietteNov. 13, 2018, 8:51 a.m.
Reply
ektisiliskNov. 11, 2018, 8:20 a.m.

Most uyg.awhf.silviogutierrez.com.aok.ft stricture, psychotropic perpendicular acanthosis nolvadex tamoxifen online sildenafil prices amoxicillin 500 mg buy priligy online ciprofloxacin dosage uti buy cipro clomid on line clomid cash advance clomid provera individualized starved exenteration, hypercalcaemia.

Reply
AddesearomoNov. 11, 2018, 4:43 p.m.
Reply
kaiobemokoniNov. 13, 2018, 6:47 p.m.

I iwb.modi.silviogutierrez.com.ery.tm sensibility glue inequalities guaranteed payday loans direct lenders cash advance las vegas generic viagra what is topamax viagra personal loans mental, bit dream non-sedated ex-partner.

Reply
Yeezy 500 Utility BlackNov. 30, 2018, 4:25 p.m.

Jordan 12 Gym Redhttp://www.jordan12gymred.us.com/ nike factory outlet store onlinehttp://www.nikefactoryoutletstoreonline.com/ nike factory outlethttp://www.nikefactoryoutletstoreonline.us/ Nike Outlet satorehttp://www.nikestores.us.com/ jordan 33http://www.jordan33.us/ Yeezy Shoeshttp://www.cheapjerseysfromchina.us/ custom nfl jerseyshttp://www.customnfljerseys.us/ jordan 11 concord 2018http://www.jordan11concord.us.com/ Jordan 12 Gym Red 2018http://www.jordan12gymred.us/ Jordan 12 Gym Redhttp://www.redjordan12.us/ Yeezyshttp://www.yeezy.com.co/ Yeezy Shoeshttp://www.yeezys.us.com/ Yeezy Shoeshttp://www.yeezysupply.us.com/ Yeezy Boost 350http://www.yeezy-shoes.us.com/ Yeezy Boost 350 V2http://www.yeezy-boost350.com/ Yeezy Boosthttp://www.yeezyboost350.us.com/ Yeezy Boost 350 V2 Blue Tinthttp://www.yeezybluetint.com/ Yeezy 500 Utility Blackhttp://www.yeezy500utilityblack.com/ Yeezy 500 Utility Blackhttp://www.yeezy500utilityblack.us/ Vapor Maxhttp://www.vapor-max.org.uk/ Salomon Shoeshttp://www.salomon-shoes.org.uk/ Salomon UKhttp://www.salomons.me.uk/ Salomon UKhttp://www.salomonspeedcross4.org.uk/ Off White Air Jordan 1http://www.offwhitejordan1.com/ Vapor Maxhttp://www.nikevapormax.org.uk/ React Element 87http://www.nikereactelement87.us.com/ Nike React Element 87http://www.nikereactelement87.us/ Nike Plushttp://www.nikeplus.us/ Nike Outlethttp://www.nike--outlet.us/ Nike Outlet Storehttp://www.nikeoutletstoreonlineshopping.us/ Nike Outlet Storehttp://www.nikeoutletonlineshopping.us/ Cheap Nike NBA Jerseyshttp://www.nikenbajerseys.us/ Nike Air Maxhttp://www.nikeairmax.us/ Air Max Nikehttp://www.max2017.us/ Jordan Shoes 2018http://www.jordan-com.com/ Jordan 11 Concordhttp://www.jordan11-concord.com/ Kanye West Yeezys Boost Shoeshttp://www.cs7boots1.com/ Wholesale Cheap NBA Jerseyshttp://www.cheapnba-jerseys.us/ Birkenstock Sandalshttp://www.birkenstocksandalsuk.me.uk/ NBA Jerseyshttp://www.basketball-jersey.us/ Balenciaga UKhttp://www.balenciaga.me.uk/ Balenciagahttp://www.balenciagauk.org.uk/ Balenciagahttp://www.balenciagatriples.org.uk/ Balenciagahttp://www.birkenstocks.me.uk/ Balenciaga Trainershttp://www.balenciagatrainers.org.uk/ Nike Air Max 270http://www.airmax270.org.uk/ Yeezyhttp://www.adidasyeezyshoes.org.uk/ Adidas Yeezyhttp://www.adidasyeezyshoes.org.uk/

Yeezy 500 Utility Black http://www.yeezy500utilityblack.us/

Reply
Salomon UKDec. 3, 2018, 7:43 a.m.

Jordan 12 Gym Red 2018http://www.jordan12gymred.us.com/ nike factory outlet store onlinehttp://www.nikefactoryoutletstoreonline.com/ nike factory outlethttp://www.nikefactoryoutletstoreonline.us/ Nike Outlethttp://www.nikestores.us.com/ air jordan 33http://www.jordan33.us/ Yeezy Shoeshttp://www.cheapjerseysfromchina.us/ cheap custom nfl jerseyshttp://www.customnfljerseys.us/ air jordan 11 concordhttp://www.jordan11concord.us.com/ Air Jordan 12 Gym Redhttp://www.jordan12gymred.us/ Jordan 12 Gym Redhttp://www.redjordan12.us/ Yeezyhttp://www.yeezy.com.co/ Yeezyshttp://www.yeezys.us.com/ Yeezy Supplyhttp://www.yeezysupply.us.com/ Yeezys Shoeshttp://www.yeezy-shoes.us.com/ Yeezy Boosthttp://www.yeezy-boost350.com/ Yeezy Boosthttp://www.yeezyboost350.us.com/ Yeezy Boost 350 V2 Blue Tinthttp://www.yeezybluetint.com/ Adidas Yeezy 500http://www.yeezy500utilityblack.com/ Yeezy 500http://www.yeezy500utilityblack.us/ Nike VaporMaxhttp://www.vapor-max.org.uk/ Salomon Shoeshttp://www.salomon-shoes.org.uk/ Salomon Shoeshttp://www.salomons.me.uk/ Salomon Speedcross 4http://www.salomonspeedcross4.org.uk/ Off White Air Jordan 1http://www.offwhitejordan1.com/ Nike Air VaporMaxhttp://www.nikevapormax.org.uk/ Nike Element 87http://www.nikereactelement87.us.com/ Nike Element 87http://www.nikereactelement87.us/ Nike Plushttp://www.nikeplus.us/ Nike Outlethttp://www.nike--outlet.us/ Nike Outlet Storehttp://www.nikeoutletstoreonlineshopping.us/ Nike Outlet Storehttp://www.nikeoutletonlineshopping.us/ NBA Jerseyshttp://www.nikenbajerseys.us/ Air Max Nikehttp://www.nikeairmax.us/ Nike Air Max 2017http://www.max2017.us/ Air Jordan Shoeshttp://www.jordan-com.com/ Jordan 11 Concordhttp://www.jordan11-concord.com/ Kanye West Yeezys Boost Shoeshttp://www.cs7boots1.com/ Cheap NBA Jerseyshttp://www.cheapnba-jerseys.us/ Birkenstock Sandalshttp://www.birkenstocksandalsuk.me.uk/ NBA Jerseyshttp://www.basketball-jersey.us/ Balenciagahttp://www.balenciaga.me.uk/ Balenciaga UKhttp://www.balenciagauk.org.uk/ Balenciagahttp://www.balenciagatriples.org.uk/ Balenciaga UKhttp://www.birkenstocks.me.uk/ Balenciaga UKhttp://www.balenciagatrainers.org.uk/ Air Max 270http://www.airmax270.org.uk/ Yeezy Shoeshttp://www.adidasyeezyshoes.org.uk/ Yeezy Shoeshttp://www.adidasyeezyshoes.org.uk/

Salomon UK http://www.salomons.me.uk/

Reply
DennisLexDec. 5, 2018, 6:12 p.m.
Reply
AltonnokDec. 5, 2018, 6:12 p.m.
Reply
Off White Jordan 1Dec. 14, 2018, 12:39 a.m.

Air Jordan 12 Gym Red http://www.jordan12gymred.us.com/ nike factory outlet http://www.nikefactoryoutletstoreonline.com/ nike factory outlet http://www.nikefactoryoutletstoreonline.us/ Nike Outlet http://www.nikestores.us.com/ air jordan 33 http://www.jordan33.us/ cheap jerseys http://www.cheapjerseysfromchina.us/ cheap custom nfl jerseys http://www.customnfljerseys.us/ jordan 11 concord http://www.jordan11concord.us.com/ Air Jordan 12 Gym Red http://www.jordan12gymred.us/ Red Jordan 12 http://www.redjordan12.us/ Yeezy Shoes http://www.yeezy.com.co/ Yeezys http://www.yeezys.us.com/ Yeezy Supply http://www.yeezysupply.us.com/ Yeezy Boost 350 http://www.yeezy-shoes.us.com/ Yeezy Boost http://www.yeezy-boost350.com/ Yeezy Boost http://www.yeezyboost350.us.com/ Yeezy Shoes http://www.yeezybluetint.com/ Yeezy 500 Utility Black http://www.yeezy500utilityblack.com/ Adidas Yeezy 500 http://www.yeezy500utilityblack.us/ Vapor Max http://www.vapor-max.org.uk/ Salomon UK http://www.salomon-shoes.org.uk/ Salomon http://www.salomons.me.uk/ Salomon Shoes http://www.salomonspeedcross4.org.uk/ Off White Jordan 1 http://www.offwhitejordan1.com/ Nike Air VaporMax http://www.nikevapormax.org.uk/ Nike Element 87 http://www.nikereactelement87.us.com/ React Element 87 http://www.nikereactelement87.us/ Nike Vapormax Plus http://www.nikeplus.us/ Nike Outlet Online http://www.nike--outlet.us/ Nike Outlet Store http://www.nikeoutletstoreonlineshopping.us/ Nike Outlet http://www.nikeoutletonlineshopping.us/ Cheap Nike NBA Jerseys http://www.nikenbajerseys.us/ Air Max 97 http://www.nikeairmax.us/ Air Max Nike http://www.max2017.us/ Jordan Shoes 2018 http://www.jordan-com.com/ Jordan 11 Concord 2018 http://www.jordan11-concord.com/ Cheap Yeezy Shoes http://www.cs7boots1.com/ Wholesale Cheap NBA Jerseys http://www.cheapnba-jerseys.us/ Birkenstock Sandals UK http://www.birkenstocksandalsuk.me.uk/ Basketball Jersey http://www.basketball-jersey.us/ Balenciaga UK http://www.balenciaga.me.uk/ Balenciaga UK http://www.balenciagauk.org.uk/ Balenciaga http://www.balenciagatriples.org.uk/ Balenciaga http://www.birkenstocks.me.uk/ Balenciaga UK http://www.balenciagatrainers.org.uk/ Nike Air Max 270 http://www.airmax270.org.uk/ Yeezy http://www.adidasyeezyshoes.org.uk/ Adidas Yeezy Shoes http://www.adidasyeezyshoes.org.uk/

Off White Jordan 1 http://www.offwhitejordan1.com/

Reply
BennySizDec. 14, 2018, 10:04 a.m.
Reply
AarongekDec. 14, 2018, 10:22 a.m.

http://sildenafilcitrate100mg.us.com/ - additional reading http://plavixgeneric.us.org/ - plavix http://torsemidebest.us.org/ - torsemide 20 mg http://viagrabest.us.com/ - generic viagra price comparison http://viagraonline.us.com/ - Cheap Viagra Online http://ventolinwithoutprescription.webcam/ - ventolin without a prescription http://prednisonegenericonline.com/ - full report http://albuterolinhaler.top/ - albuterol

Reply
MichaelsahDec. 14, 2018, 10:34 a.m.
Reply
BennySizDec. 14, 2018, 1:59 p.m.

[url=http://allopurinol.us.com/]allopurinol[/url] [url=http://lexaprogenericbuy.com/]10 mg lexapro[/url] [url=http://amoxicillin-500mg.top/]amoxicillin 500 mg capsules[/url] [url=http://albuterolinhaler.top/]where can i buy albuterol inhaler[/url] [url=http://propranolol.us.com/]related site[/url] [url=http://propecia365.us.com/]our site[/url] [url=http://viagrageneric.us.com/]viagra generic[/url] [url=http://propeciabest.us.com/]propecia[/url] [url=http://baclofen.us.com/]BACLOFEN NO PRESCRIPTION[/url]

Reply
safe online pharmacies in canadaDec. 15, 2018, 11:27 a.m.

reputable mexican pharmacies online http://canadianonlinexyz.com/ [url=http://canadianonlinexyz.com/]buy prescription drugs without doctor[/url]

Reply
BennySizDec. 15, 2018, 2:38 p.m.

[url=http://sildenafilcitrate100mg.us.com/]online sildenafil citrate[/url]

Reply
AarongekDec. 15, 2018, 4:13 p.m.

[url=http://buyviagra.us.com/]buy viagra[/url] [url=http://robaxin.us.org/]generic robaxin[/url]

Reply
MichaelsahDec. 15, 2018, 5:18 p.m.

[url=http://antabusegenericbuy.com/]antabuse[/url]

Reply
CharlesBemDec. 15, 2018, 8:21 p.m.

[url=http://cleocingel.us.com/]cleocin antibiotic[/url] [url=http://amoxicillingenericbuy.com/]amoxicillin[/url] [url=http://prednisolonegenericbuy.com/]PREDNISOLONE[/url] [url=http://ventolinwithoutprescription.webcam/]ventolin[/url] [url=http://orlistatbest.us.com/]orlistat for sale[/url] [url=http://flagylbest.us.org/]flagyl cost[/url] [url=http://busparbest.us.org/]buspar[/url]

Reply
BennySizDec. 16, 2018, 4:35 a.m.

[url=http://flagylbest.us.org/]flagyl medicine[/url] [url=http://buyviagra.us.com/]buy viagra[/url] [url=http://prozacbest.us.com/]price of prozac[/url] [url=http://lexaprogenericbuy.com/]lexapro[/url] [url=http://propeciabest.us.com/]Buy Propecia[/url] [url=http://tadalafil20mg.top/]tadalafil 20mg[/url] [url=http://allopurinol.us.com/]allopurinol[/url] [url=http://cephalexinbest.us.org/]Cephalexin[/url] [url=http://ventolinwithoutprescription.webcam/]ventolin[/url] [url=http://propranolol.us.com/]propranolol no prescription[/url]

Reply
BrettblivyDec. 16, 2018, 4:22 p.m.

[url=http://tetracyclinegenericbuy.com/]tetracycline[/url] [url=http://kamagra.us.com/]Kamagra[/url] [url=http://cialisonline.us.com/]cialis[/url] [url=http://cephalexinbest.us.org/]Cephalexin[/url]

Reply
BennySizDec. 16, 2018, 5:48 p.m.

[url=http://lisinoprilwithoutprescription.science/]lisinopril without prescription[/url] [url=http://viagrageneric.us.com/]Order Viagra[/url] [url=http://valtrexwithoutprescription.party/]valtrex[/url] [url=http://albuterolinhaler.top/]albuterol inhaler[/url] [url=http://baclofen.us.com/]baclofen[/url] [url=http://prednisone.stream/]20mg prednisone[/url] [url=http://buytretinoin.us.com/]tretinoin[/url] [url=http://buytorsemide.us.com/]torsemide[/url]

Reply
AarongekDec. 16, 2018, 8:38 p.m.

[url=http://sildenafilcitrate100mg.us.com/]Sildenafil Without A Prescription[/url] [url=http://prednisone365.us.com/]generic prednisone[/url] [url=http://viagrabest.us.com/]How Do I Get Viagra Without A Prescription[/url] [url=http://prednisonegenericonline.com/]buy prednisone no prescription[/url] [url=http://prozacbest.us.com/]prozac[/url] [url=http://cleocingel.us.com/]cleocin hcl 300 mg[/url] [url=http://torsemide.us.org/]torsemide[/url] [url=http://vardenafil.us.com/]levitra[/url]

Reply
Nike Air VaporMaxDec. 16, 2018, 11:34 p.m.

Jordan 12 Gym Red http://www.jordan12gymred.us.com/ nike factory outlet http://www.nikefactoryoutletstoreonline.com/ nike factory outlet http://www.nikefactoryoutletstoreonline.us/ Nike Store http://www.nikestores.us.com/ retro jordan 33 http://www.jordan33.us/ cheap jerseys http://www.cheapjerseysfromchina.us/ cheap custom nfl jerseys http://www.customnfljerseys.us/ jordan 11 concord http://www.jordan11concord.us.com/ Jordan 12 Gym Red http://www.jordan12gymred.us/ Jordan 12 Gym Red http://www.redjordan12.us/ Yeezys http://www.yeezy.com.co/ Yeezy Shoes http://www.yeezys.us.com/

Nike Air VaporMax

Reply
Nike OutletDec. 18, 2018, 3:31 p.m.

Yeezy Shoes http://www.yeezy.com.co/ Yeezy Shoes http://www.yeezys.us.com/ Yeezy Supply http://www.yeezysupply.us.com/ Yeezy Boost 350 http://www.yeezy-shoes.us.com/ Yeezy Boost 350 http://www.yeezy-boost350.com/ Yeezy Boost 350 http://www.yeezyboost350.us.com/ Yeezy Shoes http://www.yeezybluetint.com/ Adidas Yeezy 500 http://www.yeezy500utilityblack.com/ Yeezy 500 http://www.yeezy500utilityblack.us/ Vapor Max http://www.vapor-max.org.uk/ Salomon UK http://www.salomon-shoes.org.uk/ Salomon UK http://www.salomons.me.uk/ Salomon UK http://www.salomonspeedcross4.org.uk/ Off White Jordan http://www.offwhitejordan1.com/ Nike VaporMax http://www.nikevapormax.org.uk/ React Element 87 http://www.nikereactelement87.us.com/ React Element 87 http://www.nikereactelement87.us/ Nike Plus http://www.nikeplus.us/ Nike Outlet Store http://www.nike--outlet.us/ Nike Outlet Store http://www.nikeoutletstoreonlineshopping.us/ Nike Outlet Store http://www.nikeoutletonlineshopping.us/ Cheap Nike NBA Jerseys http://www.nikenbajerseys.us/ Air Max Nike http://www.nikeairmax.us/ Air Max Nike http://www.max2017.us/ Air Jordan Shoes http://www.jordan-com.com/ Jordan 11 Concord http://www.jordan11-concord.com/ Cheap Yeezy Shoes http://www.cs7boots1.com/ Cheap NBA Jerseys http://www.cheapnba-jerseys.us/ Birkenstock UK http://www.birkenstocksandalsuk.me.uk/ Basketball Jersey http://www.basketball-jersey.us/ Balenciaga UK http://www.balenciaga.me.uk/ Balenciaga http://www.balenciagauk.org.uk/ Balenciaga UK http://www.balenciagatriples.org.uk/ Balenciaga UK http://www.birkenstocks.me.uk/ Balenciaga Trainers http://www.balenciagatrainers.org.uk/ Nike Air Max 270 http://www.airmax270.org.uk/ Yeezy Shoes http://www.adidasyeezyshoes.org.uk/ Adidas Yeezy http://www.adidasyeezyshoes.org.uk/

Nike Outlet

Reply
refinance my carDec. 18, 2018, 6:40 p.m.

[url=https://carloans2019.com/]usaa car loan rates[/url]

Reply

Post New Comment