1
bash=${BASH_VERSION%.*}; bmajor=${bash%.*}; bminor=${bash#*.}
echo "BASH VERSION --- $BASH_VERSION"
echo "bmajor ----- $bmajor"
echo "bminor ----- $bminor"

prints,

BASH VERSION --- 4.2.46(1)-release
bash --- 4.2
bmajor ----- 4
bminor ----- 2

I normally use curly brackets, {} to work with arrays. I see here, they are used for pattern matching.

How these values, ${BASH_VERSION%.*}; bmajor=${bash%.*}; bminor=${bash#*.} are evaluated? And what does the special characters, *, ., # inside {} mean?

Janis
  • 14,222
  • You've got a quote from the man page already that explains %, %%, #, and ## inside ${...}, so I'm just answering the rest here. - The * is a shell regexp meta-character ("arbitrary string") in this context. The . is just a literal dot. - The ${...} syntax is also advantageous if you want to concatenate variables with literal strings, as in ${var}_ext which is different from $var_ext (the latter would actually mean ${var_ext}). - Shells like ksh, bash, zsh, support also yet more expressions (non-POSIX), like ${var:pos} and ${var:pos:len}. – Janis Jun 07 '15 at 04:20

1 Answers1

2

Cite from Bash reference manual:

  • ${parameter#word}

  • ${parameter##word}

    The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. ...

  • ${parameter%word}

  • ${parameter%%word}

    The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the ‘%’ case) or the longest matching pattern (the ‘%%’ case) deleted. ...

yaegashi
  • 12,326