idank / explainshell

match command-line arguments to their help text
GNU General Public License v3.0
13.13k stars 784 forks source link

Mention word splitting and globbing #129

Open ScoreUnder opened 9 years ago

ScoreUnder commented 9 years ago

screenshot

In this description it does not distinguish between the $ operator used bare and the $ operator in quotes. The bare $ operator should mention that it performs word splitting and globbing, which is almost always undesirable behaviour for a beginning scripter.

idank commented 9 years ago

Can you point me to the relevant part in 'man bash' and show an example?

ScoreUnder commented 9 years ago

Searching for "Word Splitting" (case sensitive) in man bash you will get a section mentioning half of it:

The shell scans the results of parameter expansion [...] that did not occur within double quotes for word splitting.

The next subsection "Pathname Expansion" covers globbing. It's a little less clear about the quoting behaviour here but it does eventually mention it:

The special pattern characters must be quoted if they are to be matched literally.


An example:

str='* bash says "Hello, World!" *
obligatory newline       and spaces'

echo 'Splitting/globbing behaviour when not in quotes:'
printf '<%s>\n' $str

echo 'Splitting/globbing behaviour when in double quotes:'
printf '<%s>\n' "$str"

Result:

score@kirisame ~ $ bash test-case.sh
Splitting/globbing behaviour when not in quotes:
<1435774173060.png>
<2015-07-02-230629513567520.png>
<bin>
<docs>
<downloads>
<img>
<music>
<src>
<test.bmp>
<test-case.sh>
<videos>
<vms>
<bash>
<says>
<"Hello,>
<World!">
<1435774173060.png>
<2015-07-02-230629513567520.png>
<bin>
<docs>
<downloads>
<img>
<music>
<src>
<test.bmp>
<test-case.sh>
<videos>
<vms>
<obligatory>
<newline>
<and>
<spaces>
Splitting/globbing behaviour when in double quotes:
<* bash says "Hello, World!" *
obligatory newline       and spaces>

Also worth mentioning here (and mentioned in the bash man pages somewhere) is that quoting $@ won't subject it to word-splitting or pathname expansion (as with quoting anything else), but it WILL still split $@ into its relevant list of arguments. some_other_func "$@" is a way of losslessly forwarding an argument list to another function or command. The same applies to "${array[@]}" references. These are mentioned near the top of the "EXPANSION" section of the man page.