Bash: How to Convert First Character in Variable to Uppercase


Often you may want to convert the first character in a variable to uppercase in Bash.

You can use the following methods to do so:

Method 1: Convert First Character to Uppercase

my_var="${my_var^}"

This particular example will convert only the first character of the variable named my_var to uppercase.

Method 2: Convert First Character of Each Word to Uppercase

my_var=( $my_var )
my_var="${my_var[@]^}"

This particular example will convert the first character of each word in the variable named my_var to uppercase.

The following examples show how to use each method in practice.

Example 1: Convert First Character to Uppercase in Bash

Suppose that we create a variable named my_var in Bash that contains the following text:

  • dallas mavericks

We can use the following syntax to convert only the first character of this string to uppercase:

my_var="dallas mavericks"
my_var="${my_var^}"

echo $my_var

The following screenshot shows how to use this syntax in practice:

Bash convert first character to uppercase

We can see that this returns the following string:

  • Dallas mavericks

Notice that only the first character in the string is now uppercase.

Example 2: Convert First Character of Each Word to Uppercase in Bash

Suppose that we create a variable named my_var in Bash that contains the following text:

  • dallas mavericks

We can use the following syntax to convert the first character of each word in this string to uppercase:

my_var="dallas mavericks"
my_var=( $my_var )
my_var="${my_var[@]^}"

echo $my_var

The following screenshot shows how to use this syntax in practice:

Bash convert first character of each string to uppercase

We can see that this returns the following string:

  • Dallas Mavericks

Notice that the first character of each word in the string is now uppercase.

Feel free to use whichever method you prefer.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Extract Text Between Two Strings
Bash: How to Replace Multiple Characters in String
Bash: How to Replace All Occurrences of String in File

Leave a Reply