On Sat, Dec 26, 2020 at 01:29:58PM +0100, Alessandro De Laurenzis wrote:
> Greetings,
>
> While extracting the first two characters from a string I noticed the
> following:
>
> > $ str="-- foo bar blahblahblah"
> > $ echo "First 2 chars: ${str%${str#??}}"
> > First 2 chars: --
> > $ str="-- foo bar blahblahblah [foo]"
> > $ echo "First 2 chars: ${str%${str#??}}"
> > First 2 chars: -- foo bar blahblahblah [foo]
> > $
>
> It seems that the presence of '[' and ']' is somehow disturbing the
> substitution...
>
> Quite similar behavior in bash (the only difference is that the substitution
> works there when no chars are present in between the square brackets).
>
> Is this expected?
The main issue with your code is that you need to quote the pattern to
have it be interpeted as a string an not as a shell globbing pattern:
${str%"${str#??}"}
You may also want to use printf to output variable data (it doesn't
matter in this particular case though, but would matter with bash with
the xpg_echo shell option set, if the two characters happens to be
something like \n or \t).
printf 'First 2 chars: %s\n' "${str%"${str#??}"}"
--
Andreas (Kusalananda) Kähäri
SciLifeLab, NBIS, ICM
Uppsala University, Sweden
.