6. Shell Expansions

Bash does eight different types of expansions. They are done for performing complex commands easily. The expansions are done in a defined order from left to right: brace expansion, tilde expansion, parameter expansion, arithmetic expansion, command substitution, word splitting, filename expansion, quote removal. Hence brace expansion is done before tilde expansion:

$ echo ~{pa,user19}
/home/pa /home/user19

and command substitution:

$ echo {$(echo 1,2,3)}{a,b}
{1,2,3}a {1,2,3}b

Filename expansion is done after word splitting:

$ words=(*)
$ echo ${words[@]}
0file Afile _file abcfile bfile f le fiiile fiile file fjjle fjle fle
$ echo ${#words[@]}
12

So each filename in the current directory is taken into one word by the "*" operator, even the filename "f le". The resulting array words holds 12 elements. But word splitting is done after command substitution:

$ words=($(ls))
$ echo ${words[@]}
0file Afile _file abcfile bfile f le fiiile fiile file fjjle fjle fle
$ echo ${#words[@]}
13

First all filenames in the current directory are listed by the ls command. The output of the ls command is taken into one word separated by a blanks " ". Afterwards word splitting takes place on the blank " ". "f le" is splitted into two words. Hence the resulting array holds 13 elements

As last quote removal takes place: It removes remaining unquoted escape characters "\", double """ and single quotes "'" from the expanded input. The lasting words are used to perform commands and execute them.