Skip to content

Bash

To convert Upper or mixed case of a variable to lower case

var=HeyThere
echo ${var,,}
heythere

Shell Parameter Expansion

${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

${parameter:=word} If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way.

${parameter:?word} If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

${parameter:+word} If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

${parameter:offset} ${parameter:offset:length}

This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is ‘@’, an indexed array subscripted by ‘@’ or ‘*’, or an associative array name, the results differ as described below. If length is omitted, it expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see Shell Arithmetic).

If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion.

Here are some examples illustrating substring expansion on parameters and subscripted arrays:

$ string=01234567890abcdefgh
$ echo ${string:7}
7890abcdefgh
$ echo ${string:7:0}

$ echo ${string:7:2}
78

$ echo ${string:7:-2}
7890abcdef

$ echo ${string: -7}
bcdefgh

$ echo ${string: -7:0}

$ echo ${string: -7:2}
bc

$ echo ${string: -7:-2}
bcdef

$ set -- 01234567890abcdefgh
$ echo ${1:7}
7890abcdefgh

$ echo ${1:7:0}

$ echo ${1:7:2}
78

$ echo ${1:7:-2}
7890abcdef

$ echo ${1: -7}
bcdefgh

$ echo ${1: -7:-2}
bcdef


$ array[0]=01234567890abcdefgh
$ echo ${array[0]:7}
7890abcdefgh
$ echo ${array[0]:7:0}

$ echo ${array[0]:7:2}
78

$ echo ${array[0]:7:-2}
7890abcdef

$ echo ${array[0]: -7}
bcdefgh

$ echo ${array[0]: -7:0}

$ echo ${array[0]: -7:2}
bc

$ echo ${array[0]: -7:-2}
bcde