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)
or using AWK:
foo=$(echo ${foo} | awk '{print toupper($0)}')
or with Perl:
foo=$(echo ${foo} | perl -ne 'print uc')
or using sed:
foo=$(echo ${foo} | sed 's/[a-z]/\U&/g')
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"
Now let's make the very first letter (f
) uppercase β F
:
foo=${foo^}
echo $foo
Foo
Cool! Let's now make the first letter back to lowercase:
foo=${foo,}
echo $foo
foo
Splendid! Let's make all letters uppercase:
foo=${foo^^}
echo $foo
FOO
Terrific! And back to the all lowercase again:
foo=${foo,,}
echo $foo
foo
That's all! I hope you find this post educational! Happy scripting!
Top comments (0)