Bash shell script to convert string from lower to upper case and vice versa
The “tr” command can be used to convert a string variable to upper or lower case. The following function in a bash script converts first argument to lower case.
Convert the given argument into an all lower case string.
toLower() {
echo $1 | tr "[:upper:]" "[:lower:]"
}
GENDER=MALE
GENDER=`toLower $GENDER`
echo $GENDER
Convert the given argument into an all upper case string.
toUpper() {
echo $1 | tr "[:lower:]" "[:upper:]"
}
GENDER=male
GENDER=`toUpper $GENDER`
echo $GENDER


about 2 years ago
Maybe it’s because I’m using cygwin, but I had to do:
toUpper() { echo $1 | tr “[:lower:]” “[:upper:]” ; }
Note the semicolon…
about 2 years ago
Nope. The example given in the article assumes the function to be placed in a bash script. But you are trying to fit all three lines in a single line. So you need a semi-colon.
See the following example:
[neo@techpulp ~]# toUpper() { echo $1 | tr “[:lower:]” “[:upper:]” }
> bash: syntax error: unexpected end of file
[neo@techpulp ~]# toUpper() { echo $1 | tr “[:lower:]” “[:upper:]”; }
[neo@techpulp ~]#
You can see in the first command where a semi-colon is not given, the bash is still expecting some input so I had to press Ctrl+D to get out.
But in the second command where a semi-colon is given, bash is expecting no more input.
about 1 year ago
The same can be represented in this way as well.
Lower case to Upper case:
bash# toUpper() { echo $1 | tr “[a-z]” “[A-Z]”; }
bash# toUpper myname
MYNAME
bash#
Upper case to Lower case:
bash# toLower() { echo $1 | tr “[A-Z]” “[a-z]”; }
bash# toLower MYNAME
myname
bash#
about 1 year ago
The following command helps in converting all contents of a file from lower case to upper case.
bash# tr ‘[:lower:]‘ ‘[:upper:]‘ output.txt
bash# tr ‘[:upper:]‘ ‘[:lower:]‘ output.txt