[GTALUG] bash quoting [was Re: Help need in bash]

Lennart Sorensen lsorense at csclub.uwaterloo.ca
Fri Jun 1 11:10:10 EDT 2018


On Fri, Jun 01, 2018 at 10:56:39AM -0400, D. Hugh Redelmeier via talk wrote:
> Rules for quoting in bash (or any language with macro semantics) are
> hard.  Quoting doesn't seem to be natural for humans.  Without quotes,
> data can bleed into code.
> 
> When I'm writing a bash script, I try to quote every macro use except for 
> those that must not be quoted.
> 
> The reason: without quoting, the use will probably break if there is a
> space (or other odd thing) in the value but "normal" testing rarely
> uncovers this.
> 
> UNIX/Linux folks don't think that spaces belong in pathnames but GUIs
> and the OS don't agree.
> 
> Repeat advice:
> 
> - use "set -u" to turn references to undefined macros (spelling
>   errors) into bash errors
> 
> - use "set -e" so that a shell script stops when a command returns an
>   error value that the script tacitly ignores.
> 
> bash scripts are easy to get wrong.  I've found that these habits
> expose or prevent a significant number of mistakes.  They also remove
> these issues from consideration when you are trying to puzzle out some 
> bash problem.

Oh yes quoting is fun.

$ ls
'a b c.png'   a.png   b.png   c.png

$ for f in "*.png"; do echo "$f"; done
a b c.png a.png b.png c.png

$ for f in "*.png"; do echo "$f"; done
*.png

$ for f in *.png; do echo "$f"; done
a b c.png
a.png
b.png
c.png

$ for f in *.png; do ls $f; done
ls: cannot access 'a': No such file or directory
ls: cannot access 'b': No such file or directory
c.png
a.png
b.png
c.png

Some places you must use it and some places you must not.

-- 
Len Sorensen


More information about the talk mailing list