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:]'
2

3 Answers 3

1

Use

printf '%s\n' "$a" | tr '[:upper:]' '[:lower:]'
1
  • 1
    But note: tr '[:upper:]' '[:lower:]' <<< "Å" #=> Å
    – peak
    Commented Mar 11, 2023 at 2:32
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
1
  • Alas this won't work with a='Å', at least not with bash up to and including 5.1.16
    – peak
    Commented Mar 11, 2023 at 3: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

Not the answer you're looking for? Browse other questions tagged or ask your own question.