help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] basename for n levels


From: Greg Wooledge
Subject: Re: [Help-bash] basename for n levels
Date: Wed, 10 Jun 2015 08:48:50 -0400
User-agent: Mutt/1.4.2.3i

On Wed, Jun 10, 2015 at 06:29:46AM -0600, Eric Blake wrote:
> > I seem to have failed at something pretty simple, in bash. I have a string 
> > variable that holds the full path to a directory. I'd like to assign the 
> > last two directories in it to another string. For example, if I have:
> > 
> > DIRNAME = /a/b/c/d/e
> > 
> > I'd like:
> > 
> > DIRNAME2 = d/e

Please don't use all-caps variable names.  They risk conflicting with
internal bash variables or environment variables.  (I know, Peng didn't
write that example, but it goes for everyone reading this via a Google
search in the future.)

Here's a split/join approach:

IFS=/ read -ra parts <<< "$dirname"
lasttwo=("address@hidden:(-2)}")
( IFS=/; echo "${lasttwo[*]}" )
# though personally, I would just set IFS, do the echo, and unset IFS

And here's a parameter expansion approach:

left=${dirname%/*/*}
echo "${dir#"$left"/}"

The split/join approach looks more difficult, but I find it easier to
comprehend, personally.  It's also more flexible.  If you wanted, say,
the middle two components, that would be the easier approach by far.
The parameter expansion approach is shorter, and probably runs faster
for this case, and is portable all the way back to the Bourne shell,
but it's very tricky to write.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]