BASH tr command
Pregunta
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
Solución
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.
Otros consejos
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
In bash
version 4 or greater:
answer=${answer^^*}
It is not clear what you are asking, but if you are trying to convert the user input to uppercase, just do:
sed 1q | tr '[:lower:]' '[:upper:]' | read answer
In shells that do not run the read in a subshell (eg zsh), this will work directly. To do this in bash, you need to do something like:
printf "Enter in Location (i.e. SDD-134): "
sed 1q | tr '[:lower:]' '[:upper:]' | { read answer; echo $answer; }
After the subshell closes, answer
is an unset variable.
good and clear way to uppercase variable is
$var=`echo $var|tr '[:lower:]' '[:upper:]'`
Note Bene a back quotes