How to uppercase the command line argument?

I searched SO and found that to uppercase a string following would work

str="Some string"
echo ${str^^}

But I tried to do a similar thing on a command-line argument, which gave me the following error

Tried

#!/bin/bash
             ## Output
echo ${1^^}  ## line 3: ${1^^}: bad substitution
echo {$1^^}  ## No error, but output was still smaller case i.e. no effect

How could we do this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The syntax str^^ which you are trying is available from Bash 4.0 and above. Perhaps yours is an older version (or you ran the script with sh explicitly):

Try this:

str="Some string"
printf '%sn' "$str" | awk '{ print toupper($0) }'

Method 2

echo "lowercase" | tr a-z A-Z

Output:

LOWERCASE

Method 3

Be careful with tr unless A-Z is all you use. For other locales even ‘[:lower:]’ ‘[:upper:]’ fails, only awk’s toupper and bash (v4+) works

$ str="abcåäö"
$ echo "$str"|tr '/a-z/' '/A-Z/'
ABCåäö
$ echo "$str"|LC_ALL=sv_SE tr '[:lower:]' '[:upper:]'
ABCåäö
$ echo "$str"|awk '{print toupper($0)}'
ABCÅÄÖ
$ echo ${str^^} # Bash 4.0 and later
ABCÅÄÖ
$ STR="ABCÅÄÖ"
$ echo ${STR,,}
abcåäö

Method 4

Alternatively, you could switch to ksh or zsh which have had case conversion support for decades (long before bash‘s ${var^^} added in 4.0), though with a different syntax:

#! /bin/ksh -
typeset -u upper="$1"
printf '%sn' "$upper"

(also works with zsh; note that in pdksh/mksh, that only works for ASCII letters).

With zsh, you can also use the U parameter expansion flag:

#! /bin/zsh -
printf '%sn' "${(U)1}"

POSIXLY, you can use:

awk 'BEGIN{print toupper(ARGV[1])}' "$1"

There’s also:

printf '%sn' "$1" | tr '[:lower:]' '[:upper:]'

But in a few implementations, including GNU tr, that only works for single-byte characters (so in UTF-8 locales, only on ASCII letters).

Method 5

If someone is still getting error trying ${str^^}, you can try python -c or perl It is likely because bash version is lower than 4.

But, so far bash 4 or over is working swiftly with the existing solution.

L2U="I will be upper"

Using python -c in bash

python -c "print('$L2U'.upper())"
I WILL BE UPPER

Similarly it also can be used to capitalise with:

service="bootup.sh on home"
python -c "print('$service'.capitalize())"
Bootup.sh on home

Using perl

echo $L2U | perl -ne 'print "U$_"'
I WILL BE UPPER


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x