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
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.
Unquoted
$packssends all the space-separated package names as arguments to apt-get, while quoting it sends the$packsstring as a single argument. apt-get then tries to install a package namedapache2 php php-mbstring php-mysql(for the first example), 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