BASH tr command

51,105

Solution 1

This version doesn't require bash, but uses a pipe:

read -p "Enter in Location (i.e. SDD-134) " answer
answer=$(echo "$answer" | tr '[:lower:]' '[:upper:]')
echo "$answer"

And if you're using bash and don't care about portability you can replace the second line with this:

answer="${answer^^}"

Check the "Parameter Expansion" section of bash's man page for details.

Solution 2

Echoing a variable through tr will output the value, it won't change the value of the variable:

answer='cfg'
echo $answer | tr '[:lower:]' '[:upper:]'
# outputs uppercase but $answer is still lowercase

You need to reassign the variable if you want to refer to it later:

answer='cfg'
answer=$(echo $answer | tr '[:lower:]' '[:upper:]')
echo $answer
# $answer is now uppercase

Solution 3

In bash version 4 or greater:

answer=${answer^^*}
Share:
51,105
Dan
Author by

Dan

Updated on March 04, 2020

Comments

  • Dan
    Dan about 4 years

    Id like to convert it to uppercase for the simple purpose of formatting so it will adhere to a future case statement. As I thought case statements are case sensitive.

    I see all over the place the tr command used in concert with echo commands to give you immediate results such as:

    echo "Enter in Location (i.e. SDD-134)"
    read answer (user enters "cfg"
    
    echo $answer | tr '[:lower:]' '[:upper:]'   which produced
    
    cfg # first echo not upper?
    
    echo $answer #echo it again and it is now upper...
    
    CFG
    
  • Dan
    Dan almost 12 years
    so the echo after: answer$(echo <---- does not echo in the shell?
  • Alex Howansky
    Alex Howansky almost 12 years
    Correct, it does not get output. It gets captured and assigned back to the variable.
  • sorpigal
    sorpigal almost 12 years
    This is not valid syntax for assignment; you should omit the first $
  • sorpigal
    sorpigal almost 12 years
    In bash you could just say read answer < <(tr '[:lower:]' '[:upper:]'<<<"$answer") and avoid the pipe that way.