, Johann Schmitz

The Bourne-Again Shell provides a number of built-in operators to manipulate the content of variables which is very handy when writing shell scripts or ebuilds. Other shells may also support some of them so make sure to set a proper shebang when writing your scripts (not needed in ebuilds).

Replacing / Removing

s="foobar"
echo ${s/oo/uu}
>> fuubar

s="foobar"
echo ${s/oo/} # or simplified: ${s/oo}
>> fbar

Note: using the / operator, only the first occurrence will be replaced. To replace all occurrences, use //:

s="foobar foobar foobar"
echo ${s//foo}
>> bar bar bar

Capitalize

s="foobar"
echo ${s^}
>> Foobar

Value or default

s="foo"
echo ${s:=bar}
>> foo
unset s
echo ${s:=bar}
>> bar

String length

s="foo"
echo ${#s}
>> 3

Substring

s="foobar"
echo ${s:3} # from the 4th character to the end
>> bar
echo ${s:1:2} # two characters starting from the second
>> oo

echo ${s: -3} # three characters from the end (note the space)
>> bar
echo ${s:(-3)} # same as above
>> bar