avinashse
avinashse

Reputation: 1460

Convert to uppercase in shell

I am reading a character from keyboard and converting it to uppercase and then displaying the character again.

But the following code produces an error:

read a;
a=echo $a | tr 'a-z' 'A-Z'
echo $a

I also tried this:

read option;
eval $(awk -v option=$option '{print "a="toupper(option);}')
echo $a

Upvotes: 18

Views: 80717

Answers (7)

Aman
Aman

Reputation: 8995

Use command substitution:

a=`echo $a | tr 'a-z' 'A-Z'`

Note the ticks ` around echo and tr.

Upvotes: 7

dogbane
dogbane

Reputation: 274612

This can be done natively in Bash as follows:

read a;
a="${a^^}"
echo "$a"

There is no need to invoke other commands like tr, because Bash can do this itself.

See also: Bash parameter expansion.

Upvotes: 32

Miguel Aguilar
Miguel Aguilar

Reputation: 41

using a bash script

printf "Type your Message Here: " read message

echo Upper Case: $message | tr [:lower:] [:upper:];
echo Lower Case: $message | tr [:upper:] [:lower:]

Upvotes: 4

Juergen H.
Juergen H.

Reputation: 121

AWK is the right way to convert upper/lower case with full Unicode Support ;-)

echo "öäüßè" | awk 'BEGIN { getline; print toupper($0) }'

Upvotes: 12

Andrew
Andrew

Reputation: 11

Could not get

a=`echo $a | tr 'a-z' 'A-Z'` 

to work, but

a=`echo $a | tr '[a-z]' '[A-Z]'`

did (note additional regex [] brackets.
Within a /usr/bin/sh script this worked as in

...
while getopts ":l:c:" option; do  
   case "$option"  
   in  
      l) L_OPT=`echo ${OPTARG}| tr '[a-z]' '[A-Z]'`  
         ;;  
      c) C_OPT=`echo ${OPTARG} | tr '[a-z]' [A-Z]'`  
         ;;  
      \?)  
         echo $USAGE  
         exit 1  
         ;;  
   esac  
done  
...

Upvotes: 0

Thor
Thor

Reputation: 47099

awk is the wrong way to go here, but here's one way it could be done:

a=$(awk 'BEGIN { getline; print toupper($0) }')
echo $a

Upvotes: 1

P.P
P.P

Reputation: 121387

If you want to store the result of a back in a, then you can do use command substitution:

read a;
a=$(echo $a | tr 'a-z' 'A-Z')
echo $a

Upvotes: 40

Related Questions