Variable Substitution

variable=value
Set the variable’s content to value.
${variable}
Use the value of variable. The curly brackets are optional for a string variable separated from the surrounding code; they are always required for array variables.
${variable:-value}
If the variable is set, its value is used; otherwise the specified value is used.
${#variable}
Use the length of variable.
${variable#pattern}
Use the value of variable after removing characters matching pattern from the left. This removes the shortest matching piece.
${variable##pattern}
Use the value of variable after removing characters matching pattern from the left. This removes the longest matching piece.
${variable%pattern}
Use the value of variable after removing characters matching pattern from the right. This removes the shortest matching piece.
${variable%%pattern}
Use the value of variable after removing characters matching pattern from the right. This removes the longest matching piece.
${variable/pattern/replacement}
Use the value of variable with the first match of pattern replaced by replacement.
${variable//pattern/replacement}
Use the value of variable with every match of pattern replaced by replacement.
${variable/#pattern/replacement}
Use the value of variable with match of pattern replaced by replacement at the beginning of the value.
${variable/%pattern/replacement}
Use the value of variable with match of pattern replaced by replacement at the end of the value.

From Bash version 4.0 on

${variable^^}
Transform the value of variable from lowercase to uppercase.
${variable,,}
Transform the value of variable from uppercase to lowercase.

Examples

echo ${STR:-$(date +'%F')}
echo -e ${PATH//:/\\n}
STR='/path/to/video.file.mkv'

echo ${STR##*/}            # video.file.mkv
echo ${STR##*.}            # mkv
echo ${STR%/*}             # /path/to
echo ${STR%.*}             # /path/to/video.file

echo ${STR%.mkv}           # /path/to/video.file
echo ${STR%.mkv}.mp4       # /path/to/video.file.mp4
echo ${STR/video./video_}  # /path/to/video_file.mkv
echo ${STR/./_}            # /path/to/video_file.mkv
echo ${STR//./_}           # /path/to/video_file_mkv
STR='AaaA'

# from Bash version 4.0 on 

echo "${STR^^}"  # AAAA
echo "${STR,,}"  # aaaa

# for any Bash version, as well as for UTF-8 and multibyte input

echo "${STR}" | awk '{print toupper($0)}'  # AAAA
echo "${STR}" | awk '{print tolower($0)}'  # aaaa
RED='\033[1;31m'   # red boldface
BLUE='\033[1;34m'  # blue boldface
NC='\033[0m'       # no colour, return to regular font
EM='!'             # hack for exclamation mark in double quotation; otherwise
                   # use hex \x21 inside the double quotation marks, but not
                   # octal \033

echo -e "${RED}Error${EM}${NC} Bad news.\a"
echo -e "${BLUE}All okay.${NC} Good news."

2023-05-22