1

In this question: How to convert a string to lower case in Bash?

The accepted answer is:

tr:

echo "$a" | tr '[:upper:]' '[:lower:]'

awk:

echo "$a" | awk '{print tolower($0)}'

Neither of these solutions work if $a is -e or -E or -n

Would this be a more appropriate solution:

echo "@$a" | sed 's/^@//' | tr '[:upper:]' '[:lower:]'
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
CraigScape
  • 13
  • 4
  • this comment https://stackoverflow.com/questions/2264428/how-to-convert-a-string-to-lower-case-in-bash#comment80656323_2264537 Would be nice to fix the answer. Generally: https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo – KamilCuk Apr 13 '21 at 17:05
  • Also relevant: [Why is `printf` better than `echo`?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) (oh -- now I see that's one of KamilCuk's links above) – Charles Duffy Apr 13 '21 at 17:24

3 Answers3

1

Use

printf '%s\n' "$a" | tr '[:upper:]' '[:lower:]'
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
0

Don't bother with tr. Since you're using bash, just use the , operator in parameter expansion:

$ a='-e BAR'
$ printf "%s\n" "${a,,?}"
-e bar
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Alas this won't work with a='Å', at least not with bash up to and including 5.1.16 – peak Mar 11 '23 at 03:07
0

Using typeset (or declare) you can define a variable to automatically convert data to lower case when assigning to the variable, eg:

$ a='-E'
$ printf "%s\n" "${a}"
-E

$ typeset -l a                 # change attribute of variable 'a' to automatically convert assigned data to lowercase
$ printf "%s\n" "${a}"         # lowercase doesn't apply to already assigned data
-E

$ a='-E'                       # but for new assignments to variable 'a'
$ printf "%s\n" "${a}"         # we can see that the data is 
-e                             # converted to lowercase

If you need to maintain case sensitivity of the current variable you can always defined a new variable to hold the lowercase value, eg:

$ typeset -l lower_a
$ lower_a="${a}"               # convert data to lowercase upon assignment to variable 'lower_a'
$ printf "%s\n" "${lower_a}"
-e
markp-fuso
  • 28,790
  • 4
  • 16
  • 36