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
abc:def:ghi
pbrannan@random:~> ap foo bar
pbrannan@random:~> echo $foo
:abc:def:ghi::bar
pbrannan@random:~> pp foo xyz
pbrannan@random:~> echo $foo
xyz:::abc:def:ghi::bar:
pbrannan@random:~> rp foo xyz
pbrannan@random:~> echo $foo
:::abc:def:ghi::bar::

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

What Others Think

Any idea how to format the full function so it looks right?
cout · 593 weeks and 1 day 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. https://bobscashforjunkcarsbuffalony.com/
KayGasaway · 4 weeks and 1 day 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 · 4 weeks ago
Thanks for providing recent updates regarding the concern, I look forward to read more. judi online
KayGasaway · 4 weeks 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 · 3 weeks and 5 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 · 3 weeks and 5 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. https://beyondperformances.com/
KayGasaway · 3 weeks and 5 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. http://vedadate.com/member/blog_post_view.php?postId=113668">Skin boosters treatments in East coast Singapore
KayGasaway · 3 weeks and 4 days 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 · 3 weeks and 4 days 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 · 3 weeks and 4 days 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 · 3 weeks and 4 days 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 · 3 weeks and 4 days 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 · 3 weeks and 4 days 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 · 3 weeks and 3 days 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 · 3 weeks and 2 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! http://nailsworth.vforums.co.uk/general/4094/liwovosa/p2">sleep headphones headband
KayGasaway · 3 weeks and 1 day 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 · 3 weeks and 1 day 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 · 3 weeks and 1 day 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 · 3 weeks and 1 day 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 143.198.194.222 ?to get more info
KayGasaway · 2 weeks and 5 days ago
The http://www.ukecigstore.com/">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 · 2 weeks and 5 days 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 · 1 week and 6 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 · 1 week and 6 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 · 1 week and 4 days 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 · 1 week and 1 day 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 · 4 days 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 · 2 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 https://www.piyasen.com
piyasen1 · 1 day 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 · 3 hours 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 · 2 hours 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 · 1 hour ago
????????? ?????????????????????https www ltcint org???????????????????20mg??????????????????????????????????????? ?????
KayGasaway · 15 minutes 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?

commandlinefu.com 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.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

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: