help-bash
[Top][All Lists]
Advanced

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

[Help-bash] confusion with double-hash parameter expansion


From: Ken Irving
Subject: [Help-bash] confusion with double-hash parameter expansion
Date: Fri, 25 Jan 2013 19:16:58 -0900
User-agent: Mutt/1.5.20 (2009-06-14)

I stumbled on this case where the ## parameter expansion isn't as greedy
as I thought it should be:

    $ opt=--foo
    $ echo ${opt} ${opt#-} ${opt##-}
    --foo -foo -foo

    $ echo $BASH_VERSION
    4.1.5(1)-release

There's nothing special about the dashes here, as the same result is seen
if some other character is used for the prefix.  Perhaps the reason is
that a single character is not a 'pattern', as explained in bash(1):

   Pathname Expansion
       After word splitting, unless the -f option has been set, bash
       scans each word for the characters *, ?, and [.  If one of these
       characters appears, then the  word  is regarded as a pattern, ...

I thought, then, that maybe using [-] would work, but it does not:

    $ echo $opt ${opt#[-]} ${opt##[-]}
    --foo -foo -foo

The % and %% expansions work the same way on the other end:

    $ echo $opt ${opt%o} ${opt%%o}
    --foo --fo --fo
    $ echo $opt ${opt%[o]} ${opt%%[o]}
    --foo --fo --fo

I use the 'remove matching prefix' and '... suffix' expansions quite a bit,
though more often with glob operators, and thought I knew how they worked.
Apparently not...

I get the expected results if * is used:

    $ echo $opt ${opt#*-} ${opt##*-}
    --foo -foo foo
    $ echo $opt ${opt%o*} ${opt%%o*}
    --foo --fo --f

But this would also remove any non-dash characters in the prefix, or
non-'o' characters in the suffix.

It seems to me that the pattern [-] ought to behave as I expect, with
${opt#[-]} removing one '-' and ${opt##[-]} both or all prefix dashes,
but hesitate to say this is a bug in anything but my understanding.

Ken



reply via email to

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