Show Menu
Cheatography

Bash parameter expansion Cheat Sheet (DRAFT) by

A core functionality of bash is manipulating parameters or variables. This cheat sheet shows how!

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Basic parameter usage

FRUIT="kiwi"
FRUITS=(oranges apples bananas)
echo "Today we offer $FRUITs. Maybe you like some ${FRUIT}s? We also have ${FRUITS[*]}."
Today we offer . Maybe you like some kiwis? We also have oranges apples bananas.

Parameter indire­ction

kiwi=5
fruit="kiwi"
echo "A ${fruit} costs ${!fruit} coins."
A kiwi costs 5 coins.

Case modifi­cation

boy="john"
girl="mARY"
echo "The boys name is ${boy}, properly written as ${boy^}. The girl is ${girl,,}, but I prefer ${girl~~}."
The boys name is john, properly written as John. The girl is mary, but I prefer Mary.

Substring removal

${VAR#P}
Remove pattern P from start
${VAR%P}
Remove pattern P from end
FILE
text_f­ile.txt
${FILE%.*}
text_file
${FILE­##.*}
txt
DIR
/a/b/c.txt
${DIR%/*}
/a/b
${DIR##*/}
c.txt
When working on arrays, expansion will handle each element separa­tely.
 

Search and Replace

${VAR/P/R}
Replace pattern P with R (1st occurence)
${VAR/­/P/R}
Replace pattern P with R (all occure­nces)
A
"­Dynamos can explod­e"
${A/mo­s/mite}
"­Dyn­amite can explod­e"
B
"­XXX­"
${B/#X/Y}
"­YXX­"
${B/%X/Y}
"­XXY­"

String and arry length

${#PARAM}
length of $PARAM
${#ARR[1]}
length of 2nd element in $ARR
${#ARR[@]}
number of elements in $ARR
Caution: The number of elements in an array may not reflect its highest index!

Substrings

T
A day without sunshine is like, you know, night.
${T:OFS}
OFS is the position to start
${T:32}
you know, night.
${T:(-6)}
night.
${T:OFS:L}
L is an optional length
${T:14:9}
sunshine
${T:(-­6):5}
night
ARR
(This is a text)
${ARR[­0]:2:2}
is
${arra­y[@­]:1:2}
is a
 

Default values