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
  • 96,430
  • 6
  • 33
  • 74
CraigScape
  • 13
  • 3
  • 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

0

Use

printf '%s\n' "$a" | tr '[:upper:]' '[:lower:]'
Diego Torres Milano
  • 61,192
  • 8
  • 106
  • 129
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
  • 190,037
  • 45
  • 260
  • 285
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
  • 16,615
  • 3
  • 11
  • 27