[Swan-dev] please use more double quotes in shell scripts!

D. Hugh Redelmeier hugh at mimosa.com
Sat Jul 28 17:26:46 UTC 2018


| From: Andrew Cagney <andrew.cagney at gmail.com>

| > -webdir=$(cd $(dirname $0) && pwd)
| > +webdir="$(cd "$(dirname $0)" && pwd)"
| 
| Actually, no.  In this context, the outer quotes are not needed

True.

| and
| should not be used.

Why?

|  When this was was explained to me, it came with
| the phrase common beginner's mistake :-).

I don't see why it is a mistake.  Redundant, yes.

The actual rules for assignment are odd.  They flow out of the design:
an assignment is a word.  This, I suggest, is rather unnatural and
leads to confusion.

In general, I would recommend quoting every right-hand side of an
assignment word.  It's certainly not necessary if only the (sub)word
is intended and the subword is obvious.

To me
	x=false
does seems as good as
	x="false"

But
	x=y\ z
does seem worse than
	x="y z"

|  I'm still fixing my
| scripts:
| 
| charlie$ x="a b c" # needed
| charlie$ echo "${x}"
| a b c

Yes.

	x = a b c
Invoke the command x with four arguments.

	x= a b c

Invoke the command a, with x set to "" in its environment, and two
arguments.

	x=a b c

Invoke the command b, with x set to "a" in its environment, and one
argument.

Sheesh.

| charlie$ y=$x # not needed

But identical in meaning to

	y="$x"

(I think.)

| charlie$ echo "${y}"
| a b c
| charlie$ z=$(echo "${y}")
| charlie$ echo "${z}"
| a b c
| charlie$ echo $SHELL
| /bin/sh

| As for the inner quote, if someone has spaces in a directory path then
| this is the least of their problems so I'm not fussed.

That's a terrible attitude for security critical code.  We should
aspire to bullet-proof code.

Our tests are not security-critical.  But it is good practice to be
careful throughout our project.  It is good to be safe by convention
(the less thought required the better).

The simplest convention is The Rule I stated.

        Always quote uses of '$' UNLESS you have a reason why you must
        not.  The usual reason is that the thing is a list that must be
	split into separate words.

Example of when you need splitting:

	FILES="a.c b.c c.c"
	cc $FILES

(This is a bit fragile since the filenames had better not include 
whitespace.)


More information about the Swan-dev mailing list