Usefulness of word splitting
suggest changeThere are some cases where word splitting can be useful:
Filling up array:
arr=($(grep -o '[0-9]\+' file))
This will fill up arr with all numeric values found in file
Looping through space separated words:
words='foo bar baz' for w in $words;do echo "W: $w" done
Output:
W: foo W: bar W: baz
Passing space separated parameters which don’t contain white spaces:
packs='apache2 php php-mbstring php-mysql' sudo apt-get install $packs
or
packs=' apache2 php php-mbstring php-mysql ' sudo apt-get install $packs
This will install the packages. If you double quote the $packs then it will throw an error.
Unquoetd $packs is sending all the space separated package names as arguments to apt-get, while quoting it will send the $packs string as a single argument and then apt-get will try to install a package named apache2 php php-mbstring php-mysql (for the first one) which obviously doesn’t exist
See what, when and why for the basics.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents