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: Stephane Chazelas
Subject: Re: [Help-bash] basename for n levels
Date: Wed, 10 Jun 2015 14:23:33 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

2015-06-10 08:48:50 -0400, Greg Wooledge:
> 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)}")
[...]

That assumes $dirname doesn't contain newline characters.

IFS=/; set -f
parts=($dirname)

would not have the problem and also avoid the temp file
creation.

You can even make it POSIX sh syntax with:

IFS=/; set -f
set -- $dirname
shift "$(($# - 2))" || exit
printf '%s\n' "$*"

For a truly "robust" solution, one probably would have to
consider what to do with values of dirname like:

a/b/c/
a/b//c//
a
a/b/./c
a/b/../c

-- 
Stephane




reply via email to

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