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

D. Hugh Redelmeier hugh at mimosa.com
Wed Jul 25 15:12:50 UTC 2018

The Bourne Shell and all relatives are very unforgiving about requiring 
quoting.  Most uses of $ should be quoted to avoid surprises.

It's easy to not bother, and the result usually works, but that's just not 
good enough when scripting.

For example, a filename can have a space in it.  This is not common with
traditional UNIX folks, but perfectly legal, and it shows up more and
more often when GUIs are used.  And why not?  The main reason is that
shell parsing makes this a little awkward.

But whitespace in filenames is not the only version of the problem.  Other 
metacharacters might need to be neutralized.

This problem is well known to web developers because they have to deal 
with hostile users.  So it amused me that the example sparking this post 
is in our testing/web directory.

Nothing in testing/ could spark a CVE.  We should check our shell
scripts that could.

My untested changes to testing/web/gime-git-description.sh are below.
First I'll highlight some points about those changes.

- The following looks odd because the inside quotes are not
  backslashed.  It works because the (usefully) peculiar interaction
  of SH rules.  There are too many complexities lurking in SH.

	webdir="$(cd "$(dirname $0)" && pwd)"

- I didn't quote $# because I "know" that it could not have
  meta-characters within it.  (Yes, I just used "scare-quotes" in that
  sentence.)  But this goes against The Rule:

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

- In this, I group a couple of macro references within one quote.

	echo "${version}-${branch}"

  A more straight-forward application of The Rule would result in:

	echo "${version}"-"${branch}"

  Perhaps straight-forward should win.

diff --git a/testing/web/gime-git-description.sh b/testing/web/gime-git-description.sh
index f653adfc2..2777f505b 100755
--- a/testing/web/gime-git-description.sh
+++ b/testing/web/gime-git-description.sh
@@ -18,7 +18,7 @@ fi
 set -eu
-webdir=$(cd $(dirname $0) && pwd)
+webdir="$(cd "$(dirname $0)" && pwd)"
 # cd to the repo
 if test $# -gt 0 ; then
@@ -26,6 +26,6 @@ if test $# -gt 0 ; then
-version=$(git describe --long)
-branch=$(${webdir}/gime-git-branch.sh .)
-echo ${version}-${branch}
+version="$(git describe --long)"
+branch="$("${webdir}"/gime-git-branch.sh .)"
+echo "${version}-${branch}"

More information about the Swan-dev mailing list