Bash shell script to convert string from lower to upper case and vice versa
In Category Bash
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
Maybe it’s because I’m using cygwin, but I had to do:
toUpper() { echo $1 | tr “[:lower:]” “[:upper:]” ; }
Note the semicolon…
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.