DEV Community

Petr Razumov
Petr Razumov

Posted on

2 2

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!

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more