DEV Community

Petr Razumov
Petr Razumov

Posted on

How to make variable values UPPERCASE or lowercase in Bash

When we need to transform some Bash variable value into, for example, uppercase, we often use some pipelines like the followings:

foo="foo"

foo=$(echo ${foo} | tr a-z A-Z)
Enter fullscreen mode Exit fullscreen mode

or using AWK:

foo=$(echo ${foo} | awk '{print toupper($0)}')
Enter fullscreen mode Exit fullscreen mode

or with Perl:

foo=$(echo ${foo} | perl -ne 'print uc')
Enter fullscreen mode Exit fullscreen mode

or using sed:

foo=$(echo ${foo} | sed 's/[a-z]/\U&/g')
Enter fullscreen mode Exit fullscreen mode

However, it is possible to achieve the same results just using pure Bash! And it's fantastically easy to do!

Let's start with defining the variable and its value:

foo="foo"
Enter fullscreen mode Exit fullscreen mode

Now let's make the very first letter (f) uppercase β€” F:

foo=${foo^}
echo $foo
Foo
Enter fullscreen mode Exit fullscreen mode

Cool! Let's now make the first letter back to lowercase:

foo=${foo,}
echo $foo
foo
Enter fullscreen mode Exit fullscreen mode

Splendid! Let's make all letters uppercase:

foo=${foo^^}
echo $foo
FOO
Enter fullscreen mode Exit fullscreen mode

Terrific! And back to the all lowercase again:

foo=${foo,,}
echo $foo
foo
Enter fullscreen mode Exit fullscreen mode

That's all! I hope you find this post educational! Happy scripting!

Top comments (0)