path manipulation in bash

rp() { local p; eval p=":\$$1:"; export $1=${p//:$2:/:}; }; ap() { rp "$1" "$2"; eval export $1=\$$1$2; }; pp() { rp "$1" "$2"; eval export $1=$2:\$$1; }
I used to do a lot of path manipulation to set up my development environment (PATH, LD_LIBRARY_PATH, etc), and one part of my environment wasn't always aware of what the rest of the environment needed in the path. Thus resetting the entire PATH variable wasn't an option; modifying it made sense. The original version of the functions used sed, which turned out to be really slow when called many times from my bashrc, and it could take up to 10 seconds to login. Switching to parameter substitution sped things up significantly. The commands here don't clean up the path when they are done (so e.g. the path gets cluttered with colons). But the code is easy to read for a one-liner. The full function looks like this: remove_path() { eval PATHVAL=":\$$1:" PATHVAL=${PATHVAL//:$2:/:} # remove $2 from $PATHVAL PATHVAL=${PATHVAL//::/:} # remove any double colons left over PATHVAL=${PATHVAL#:} # remove colons from the beginning of $PATHVAL PATHVAL=${PATHVAL%:} # remove colons from the end of $PATHVAL export $1="$PATHVAL" } append_path() { remove_path "$1" "$2" eval PATHVAL="\$$1" export $1="${PATHVAL}:$2" } prepend_path() { remove_path "$1" "$2" eval PATHVAL="\$$1" export $1="$2:${PATHVAL}" } I tried using regexes to make this into a cleaner one-liner, but remove_path ended up being cryptic and not working as well: rp() { eval "[[ ::\$$1:: =~ ^:+($2:)?((.*):$2:)?(.*):+$ ]]"; export $1=${BASH_REMATCH[3]}:${BASH_REMATCH[4]}; };
Sample Output
pbrannan@random:~> foo="abc:def:ghi"
pbrannan@random:~> echo $foo
pbrannan@random:~> ap foo bar
pbrannan@random:~> echo $foo
pbrannan@random:~> pp foo xyz
pbrannan@random:~> echo $foo
pbrannan@random:~> rp foo xyz
pbrannan@random:~> echo $foo

By: cout
2010-07-15 18:52:01

What Others Think

Any idea how to format the full function so it looks right?
cout · 601 weeks and 5 days ago
junkyards in Buffalo Are you looking to sell your junk car for cash in Buffalo, NY-Buffalo Junkyard provides the best cash offer with free towing service in Buffalo and surrounding areas.
KayGasaway · 12 weeks and 5 days ago
Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject. digital agency
KayGasaway · 12 weeks and 3 days ago
Thanks for providing recent updates regarding the concern, I look forward to read more. judi online
KayGasaway · 12 weeks and 3 days ago
Pretty good post. I have just stumbled upon your blog and enjoyed reading your blog posts very much. I am looking for new posts to get more precious info. Big thanks for the useful info. what is a routing number
KayGasaway · 12 weeks and 2 days ago
The betting it can make real money. play football to be rich No minimum football betting UFABET online gambling website online football betting online baccarat betting Walk online through the best system. no minimum bet Use the service ????????????????
KayGasaway · 12 weeks and 2 days ago
Bar and Chain Oil Beyond Performances is an Amsoil Dealer that provides the best Amsoil diesel oil, amsoil motor oil, best transmission fluid, and engine lubricants.
KayGasaway · 12 weeks and 2 days ago
The Best Skin boosters treatments in East coast Singapore - Perfect Beauty Bedok. Skin Origins Centre, The best facial in Bedok is at Perfect Beauty Bedok Established in 2001 Qualified beauticians using Skin Origins and Phyris. Call Us Mobile: +6593895687 or visit our website, Thank You.">Skin boosters treatments in East coast Singapore
KayGasaway · 12 weeks and 1 day ago
Revexpo is one of the True best video reviews website in India provides video reviews from online buyers & their experience, Click here ?to visit website for more information. Thank You.
KayGasaway · 12 weeks and 1 day ago
About magnetic eyelashes, all styles of eyelashes, we have can be made into magnet eyelashes. Liruijie eyelashes factory has obtained a patent for magnetic eyelashes supplier, Liruijie eyelash extension factory can guarantee its quality.
KayGasaway · 12 weeks and 1 day ago
Haiyuan food box machine company has product debugging plant, product development plant, and training plant. The production line can produce products: fast food box machine, take away food box making machine ?, PSP foam sheet, disposable fast food box, foam box machine, aquatic plate, supermarket plate, cake plate and other products. Customers ordering equipment, can accept free technical training.
KayGasaway · 12 weeks and 1 day ago
LumusSolem is a leading solar light manufacturer and supplier of solar street lights and solar powered flood lights ?that are inspired by innovative research in market trends
KayGasaway · 12 weeks ago
Triumphant Zoe Pty Ltd (Property), the place where we bring your plans to life. Visit our website for Priced Bills of Quantities Construction. We offer Property Development, Property Investment, Project Management, Quantity Surveying. We believe in removing limitations out of the equation and exceeding your expectations by providing a service that is of a high calibre of quality, that is cost effective as well as delivering results timely.
KayGasaway · 12 weeks ago
Shop our selection of beautiful Beautiful tarot decks, astrology Tarot cards, modern Tarot cards, and black and white Tarot cards for sale as well as astrology Oracle cards, angel Oracle cards, and spirit animal Oracle cards.
KayGasaway · 12 weeks ago
Elevate your productivity with our software iso 9001. Free Trial QUALITYWEB 360 for 14 days and convince yourself we are the best option to get the ISO 9001 Certification.
KayGasaway · 11 weeks and 6 days ago
Explore Dormi Dream headphones are the most comfortable sleep sleep headphones headband. Secured in a soft headband, they are comfortable even for side-sleepers. Shorter charging time, a thinner headband are the most comfortable headphones to sleep in Shop now! & and get 10% OFF your order!">sleep headphones headband
KayGasaway · 11 weeks and 5 days ago
Molds are fungi that grow on surfaces, in porous materials, and on or within living organisms and decaying organic matter. You could be living with mold and your health could be suffering. Get to the root of the problem with a hassle-free and affordable Certified mold inspector. Call us Today by visiting our website and Schedule a Mold Inspection in Columbus Ohio. Certified mold inspector
KayGasaway · 11 weeks and 5 days ago
Premium eyelid anti aging device that helps treat sagging eyelid skin. EvenSkyn:registered: is a manufacturer of premium , Laser Hair Removal, Anti Aging, andhelping men and women have smooth, hair free skin, Please click to visit our website for more information, Thank You. Site
KayGasaway · 11 weeks and 5 days ago
Vitamin C is now available in the form of injections. These VC Vitamin C Injection ?come in ampules of 1000mg and are present in the market in well-formulated states.
KayGasaway · 11 weeks and 4 days ago
Explore SGTOTO adalah bandar togel SGP online terpercaya dengan Game Slot online, Live Casino, Roulette Online, Baccarat Online, Dadu Online Judi Bola Dan Tembak Ikan. Visit ?to get more info
KayGasaway · 11 weeks and 2 days ago
The">UK ECIG STORE ?has the best range of vape devices and e liquids including starter ecig kits and pod vape kits We offer FREE UK delivery. Sign up to our newsletter today and receive 10% OFF your first order. You can unsubscribe at any time. Want to know what you need to start vaping? What a pod kit is? Please click here and get all these details. Thank You.
KayGasaway · 11 weeks and 1 day ago
Explore bim modeling services ?as Team4bim offers very low prices and we provide services fast with good quality standards, Click here & get the best offer for BIM Services and BIM Modeling.
KayGasaway · 10 weeks and 3 days ago
Buy Solar street lights in the Philippines | NATIV Techniks Inc. Nativ Techniks Inc promotes green energy ideas Our solar energy solutions are designed to improve the quality of life of Filipinos. Please visit our website for more info, Thank You. Solar street lights in the Philippines
KayGasaway · 10 weeks and 3 days ago
If You are looking for securities fraud attorney ?, Mdf Law has Decades of Legal Experience with Proven track record. Our attorneys represent investors in securities fraud claims pursued in state and federal court. These claims generally allege fraud made in connections with the offer or sale of a security. Please click here to visit our website, Thank You.Securities litigation claims may also include shareholder right’s litigation as well as derivative lawsuits. We have experience litigating these claims in state and federal court.
KayGasaway · 10 weeks and 1 day ago
Betflix adalah salah satu situs yang sudah menjadi partner resmi dari provider - provider kelas dunia yang berkualitas seperti Pragmatic Play, SpadeGaming, PlayTech, JokerGaming, Pretty Gaming, Asia Gaming, SBOBET dan masih banyak lagi pilihan yang tersedia yang bisa membuat anda tidak akan bosan.
KayGasaway · 9 weeks and 5 days ago
Send or Sell Food to the USA ? By US FDA regulations , you always need a FDA Prior Notice Confirmation ?before the shipment enters the US to avoid abandonments, returns or delays. Now it is easy to get FDA Prior Notice Form & FDA Approval for less than $1, Looking for Bulk price or Custom solution ? Visit our site.
KayGasaway · 9 weeks and 1 day ago
Explore Event Rent Now & find the Results For Mobile Bartenders Listings, Let’s uncover the Mobile Bartenders ?services near you. We connect you with local event services. Popular Exclusive Listings In Our Directory, Nearly 80% Of Consumers Turn To Directories With Reviews To Find A Local Business.
KayGasaway · 8 weeks and 6 days ago
Piya Sen Kolkata Escorts Our Elite Call Girls and VIP escort in Kolkata are waiting independent Female Model Housewife Girl Escorts Agency +917595811660
piyasen1 · 8 weeks and 4 days ago
Find out Professional business plans writer ?in UK for All necessary content written for your business plan. Comprehensive market research, Projected cash flow forecasts and profit and loss accounts. Additional business advice and guidance if needed. Contact me today to plan for your business success.
KayGasaway · 8 weeks and 3 days ago
Explore the amzaing Gamge. Online Gamecock ???????????? ?is bringing two chickens to collide or fight each other by a chicken that is good at playing, frequent and hurtful, will have a high chance of winning. But sometimes it's measured in durability. Gamecock is a traditional sport who have been with Thai people for a long time from studying history.
KayGasaway · 8 weeks and 3 days ago
Make Your Yoga & mindfulness coach ?Practice Matter, Explore Nicole Griffin site to know how to put your practice in action to create a kinder and more equitable world for all. Please visit our website for more information.
KayGasaway · 8 weeks and 3 days ago
????????? ?????????????????????https www ltcint org???????????????????20mg??????????????????????????????????????? ?????
KayGasaway · 8 weeks and 3 days ago
Rayson pp nonwoven spunbond ?fabric manufacturer is capable of OEM, ODM, or custom non woven fabric service in various colors and sizes. And Rayson will give worldwide customers a reasonable and lower pp spunbond nonwoven fabric price offer.
KayGasaway · 8 weeks ago
Car rental with driver Vietnam company offers a car rental with the driver for your tours or business activities in Vietnam. Easy to book a private car with a professional driver. Are you looking for a quote? how much dose it cost to rent a car with driver 1 day in Vietnam?It just 65$USD/day/8hrs for a private car rental in Vietnam.
KayGasaway · 7 weeks and 6 days ago
8 of the closest presidential race ??Elections Ever Do you remember any of these nailbiters. These facts will leave you to wonder why the competitiveness was so high in the presidential elections from the late 19th century. And additionally, why are we seeing the closest presidential elections in US history currently
KayGasaway · 7 weeks and 6 days ago
grand central stations are really built with some great architectural design, they are very impressive., VISA DE VISITANTE DE INDIA
wenilak444 · 7 weeks ago
Thanks for sharing this! Great stuff! furnace repair near me
frank214 · 6 weeks and 5 days ago
So great - literally amazing symptom checker app
frank214 · 6 weeks and 5 days ago
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. mr supplements
Coleman632 · 6 weeks ago
I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. supplement store near me
Coleman632 · 5 weeks and 6 days ago
This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value. Im glad to have found this post as its such an interesting one! I am always on the lookout for quality posts and articles so i suppose im lucky to have found this! I hope you will be adding more in the future... World new updates
Coleman632 · 5 weeks and 4 days ago
Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work. BUY FURANYL-FENTANYL 1:25 HCL EU POWDER
Coleman632 · 5 weeks and 2 days ago
You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. ?? ??
Coleman632 · 5 weeks ago
I am definitely enjoying your website. You definitely have some great insight and great stories. Concrete Tampa
madmardigan · 2 weeks and 6 days ago
Great info! I recently came across your blog and have been reading along. I thought I would leave my first comment. I don’t know what to say except that I have. hawaii home remodel
arlensurreali · 2 weeks and 6 days ago
I am energetic to find your perceived technique for forming the post. By and by you make it straightforward for me to fathom and execute the thought. Thankful to you for the post.
marosol · 2 weeks and 3 days ago
There is noticeably a lot of money to know about this. I assume you made certain nice points in features also.">BabyLoungers
wenilak444 · 2 weeks and 1 day ago
Shop Sterling Silver Hoop Earrings and Moissanite Stud Earrings for Women at Affordable and Cheap Prices, Allegra N Co Offering Collective range of Sterling Silver Earrings for Women, Free Delivery across the US, Click here to get 10% discount on your first purchaes. Don't miss it. Shop sterling silver earrings for women, Affordable & Cheap Prices.
KayGasaway · 3 days ago
Woah! This is an excellent article! Thank you for providing these suggestions.
jamesM · 1 day ago
At">Omaha Well Drilling & Treatment Services we offer pressure tanks, water conditioning options, and well pump installation & repair services for residential customers. If you've been considering having a well installed, call to speak with one of our specialists today!
jamesM · 21 hours ago
Omaha Well Drilling & Treatment Services We offer pressure tanks, water conditioning options, and well pump installation & repair services for residential customers. If you've been considering having a well installed, call to speak with one of our specialists today!
jamesM · 21 hours ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: