14
read -p "Enter yes/no   " SOMEVAR

SOMEVAR=`"echo ${SOMEVAR,,}"`

The code above gives me a ${SOMEVAR,,}: bad substitution error.

1 Answer 1

21

The parameter expansion ${variable,,} would expand to the value of $variable with all character in lower case in the bash shell. Given that you get a "bad substitution" error when this code runs suggests that you are in fact either

  • not using that shell but possibly /bin/sh (which is not always bash). But not getting an error for read -p suggests that it's more likely that you are
  • using an older release of bash which does not support this expansion (introduced in release 4 of bash).

The generic form of the expansion is ${variable,,pattern} in which all characters in $variable that matches pattern would be converted to lower case (use ^^ to convert to upper case):

$ str="HELLO"
$ printf '%s\n' "${str,,[HEO]}"
heLLo

See also the bash manual on your system.


For older releases of bash, you could instead do the following to lowercase the value of a variable:

variable=$( tr 'A-Z' 'a-z' <<<"$variable" )

This passes the value of the variable through tr using a "here-string". The tr utility transliterates all characters in the A to Z ASCII range (assuming the C/POSIX locale) to the corresponding character in the a to z range.


Note also that

SOMEVAR=`"echo ${SOMEVAR,,}"`

is better written as

SOMEVAR=${SOMEVAR,,}

In fact, what you wrote would give you a "command not found" error in bash release 4+, unless you have a command called echo string, including the space (where string was what the user inputted). This is due to the command substitution trying to execute the double quoted string.

15
  • 5
    or they have a pre-4.0 Bash (like the 3.2 on Macs)
    – ilkkachu
    Feb 12, 2019 at 20:54
  • 1
    @HitanshuSachania If it's macOS, then I would not recommend replacing the /bin/bash binary with a newer version.
    – Kusalananda
    Feb 13, 2019 at 8:54
  • 2
    @HitanshuSachania if they really have a bash version 3.2, then they're probably using Ubuntu 8.04 since that was the last one to ship with a 3.2 bash. That's almost 11 years old! Using software that old is an enormous security risk. In fact, there is a whopping huge bug in bash itself. That should be a good way of convincing them to upgrade although any sysadmin who has allowed this to happen is a bigger security risk than the bugs themselves.
    – terdon
    Feb 13, 2019 at 17:49
  • 1
    @HitanshuSachania Still, that's from 2009 (end of support in 2010) and the bash installed on it would likely be a security risk in itself.
    – Kusalananda
    Feb 13, 2019 at 18:03
  • 1
    @Kusalananda I shall take this point to them. Thank you for all your help. Feb 13, 2019 at 18:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .