8

I tried to convert a lowercase string to uppercase and assign it to a variable using the following code

The script is written in .tn extension

set y a12 y_up=$( tr '[A-Z]' '[a-z]' <<< $y) echo $y echo $y_up 

But I am getting the error

invalid command name "A-Z" while executing "A-Z" invoked from within "y_up=$( tr '[A-Z]' '[a-z]' <<< $y) " 

How can I convert this?

1
  • 1
    set does not what you think it does... Commented Feb 13, 2014 at 6:25

4 Answers 4

13

BASH 4+ version has native way to convert sting to upper case:

str="Some string here" upperStr="${str^^}" 
Sign up to request clarification or add additional context in comments.

Comments

12

Below Works, Try this.

bash-3.2$echo lower to upper | tr '[:lower:]' '[:upper:]' LOWER TO UPPER # To Save in the variable use below var=$(echo lower to upper | tr '[:lower:]' '[:upper:]') 

1 Comment

Actually I am writing these in .tn script , there it is still showing the error that :lower: command not found
2

This should work:

$ y="Foo Bar Baz" $ y_up=$(tr '[A-Z]' '[a-z]' <<< $y) $ echo $y_up foo bar baz 

1 Comment

This is an old answer, but it actually does the opposite of what is asked in the question: it converts uppercase letters to lowercase. The tr command should look like: tr '[a-z]' '[A-Z]'
0

Starting from Bash 5.1, you can also use the @U parameter transformation to convert all lowercase characters in parameter expansions into uppercase characters.

For example:

s="hello, wORLd!" echo "${s@U}" # HELLO, WORLD! 

And for your exact case:

y="a12" y_up="${y@U}" echo $y # a12 echo $y_up # A12 

This also saves you from making an extra call to tr , which would incur a slight performance overhead since tr is not a shell builtin and therefore requires making syscalls to fork() and exec() to execute.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.