What's New in Bash Parameter Expansion

Nod

Executive Member
Joined
Jul 22, 2005
Messages
8,624
#1
Source: https://www.linuxjournal.com/content/whats-new-bash-parameter-expansion
The bash man page is close to 40K words. It's not quite War and Peace, but it could hold its own in a rack of cheap novels. Given the size of bash's documentation, missing a useful feature is easy to do when looking through the man page. For that reason, as well as to look for new features, revisiting the man page occasionally can be a useful thing to do.

The sub-section of interest today is Parameter Expansion—that is, $var in its many forms. Don't be confused by the name though, it's really about parameter and variable expansion.

I'm not going to cover all the different forms of parameter expansion here, just some that I think may not be as widely known as others. If you're completely new to parameter expansion, check out my ancient post or one of the many articles elsewhere on the internet.
Case Conversion
Gone are the days of using tr '[[:lower:]]' '[[:upper:]]' to convert strings to uppercase:
Bash:
$ a=hello
$ echo ${a^}       # First character only
Hello
$ echo ${a^^}      # All characters
HELLO

And for going to lowercase:
Bash:
$ a=HELLO
$ echo ${a,}       # First character only
hELLO
$ echo ${a,,}      # All characters
hello

You also can specify a character after the operator and change
the case only of characters that match:
Bash:
$ a=hello
$ echo ${a^l}      # First character if it is an 'l'
hello
$ echo ${a^^ll}    # All characters that are 'l's
heLLo
more at the link
 
Top