uppercase first character in a variable with bash

I want to uppercase just the first character in my string with bash.

foo="bar";

//uppercase first character

echo $foo;

should print "Bar";


Solution 1:

One way with bash (version 4+):

foo=bar
echo "${foo^}"

prints:

Bar

Solution 2:

foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"

Solution 3:

One way with sed:

echo "$(echo "$foo" | sed 's/.*/\u&/')"

Prints:

Bar

Solution 4:

$ foo="bar";
$ foo=`echo ${foo:0:1} | tr  '[a-z]' '[A-Z]'`${foo:1}
$ echo $foo
Bar

Solution 5:

To capitalize first word only:

foo='one two three'
foo="${foo^}"
echo $foo

One two three


To capitalize every word in the variable:

foo="one two three"
foo=( $foo ) # without quotes
foo="${foo[@]^}"
echo $foo

One Two Three


(works in bash 4+)