help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] inconsistency in expansions


From: Greg Wooledge
Subject: Re: [Help-bash] inconsistency in expansions
Date: Mon, 7 May 2012 09:09:57 -0400
User-agent: Mutt/1.4.2.3i

On Mon, May 07, 2012 at 06:55:44AM -0600, Bill Gradwohl wrote:
> On Mon, May 7, 2012 at 6:29 AM, Greg Wooledge <address@hidden> wrote:
> 
> > On Sun, May 06, 2012 at 01:24:09PM -0600, Bill Gradwohl wrote:
> > > set -- "The cat " "ate the " "canary"
> > > echo $#
> > > x=$#
> > > declare string
> > > string="${*%${$#}}"
> >
> > What the bloody hell is that supposed to DO?
> >
> > Sorry - I thought it was obvious. I want all of the passed parameters in
> one string, except the last passed parameter for how ever many parameters
> there are.

OK... that's two things.  "I want to delete the last parameter", and "I
want to concatenate all the remaining ones into a single string".

I don't understand why these two things would be desirable together,
but if that's really what you want....

allbutone=("${@:1:$#-1}")
allbutone_concatenated="${allbutone[*]}"

Set IFS to whatever join-character you want.  By default, you'll get one
space between each parameter during the concatenation.

> I got 3 different results, when I was expecting 1 result. I want to
> understand how each is different, and WHY I got the results I got.

Honestly?  It's because you threw a bunch of random punctuation at
the screen.  I have a strong dislike of reverse engineering people's
non-working code.  I'd much rather produce the correct code in the
first place.

The positional parameters are like a pseudo-array.  Most of bash's array
manipulation syntax works on the positional parameters.

Thus, if you want all but the last positional parameter, you can treat
them as a non-sparse array indexed from 1 via the "@" parameter.  Hence,

allbutone=("${@:1:$#-1}")

which generates a list of words by taking a "slice" of an array, and then
assigns this list of words to a new array.  The "array" that we're slicing
is "@", which is the positional parameters.  We start at element 1, and we
take $#-1 elements.  Since we're using the "address@hidden" (quoted) version, 
each
element is emitted as a single word, even if it has internal whitespace.

Then we assign this list to the "allbutone" array.  This will be 0-indexed
since that is the default for all arrays other than "@".



reply via email to

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