Re: [dev] Shell style guide

From: Evan Gates <>
Date: Thu, 8 Sep 2016 06:47:23 -0700

On Thu, Sep 8, 2016 at 5:44 AM, Nick <> wrote:
> I think this is something one learns with time. There are several
> good reasons not to quote substitutions, such as passing multiple
> arguments to another program (e.g. cmd $_AT_), or a for or case
> statement. But yes, quoting is essential most of the time. Shell
> escaping sucks, though, obviously. Another reason to keep bourne
> shell very simple.

No. $_AT_ is another example of something that _must_ be quoted every
time. When inside quotes the shell expands it correctly to a word for
each parameter. Without quotes the shell will do extra word splitting
and globbing. For example, try this:

nargs() { echo "$#"; }
set -- foo 'bar baz'
echo "$#"
nargs "$_AT_"
nargs $_AT_

When in a case statement should you not quote? I can't think of any examples.

> I actually never use functions in shell scripts; I consider any
> script that needs them too complex to use shell. I wouldn't be
> opposed to storing a command name in a string, though, say to store
> something along the lines of 'convert' vs 'gm convert'.

I'm opposed to this. If you want convert, write convert. If you want
gm convert, write gm convert. If you want to be able to change it
everywhere in your script at once, put it in a function. Functions
exist for exactly this reason. (That was strongly worded. If you write
code that won't break, that's fine, but putting commands in variables
obfuscates the code.)

> I prefer backticks, because nesting commands is a terrible idea in
> shell scripts. Keep intermediate output in other variables, if you
> need to. But if I see nested commands in a shell script there's a
> high chance I'll rewrite it, if I'm likely to need to actually use /
> maintain it.

If you want to use intermediate variables that's fine. Sometimes they
make the code more clear, sometimes they make it less clear. I'm just
against all the syntax horror that goes on with backticks.

> I disagree. GNU ls may be, but it isn't supposed to be that way.
> Something like `ls -tr | tail -n 1` seems perfectly reasonable to
> me, for example. Sure you could use find, but for some cases ls is
> simpler.

Simpler maybe, but incorrect. Filenames can contain newlines
(filenames can contain everything but a / and a nul byte).
Received on Thu Sep 08 2016 - 15:47:23 CEST

This archive was generated by hypermail 2.3.0 : Thu Sep 08 2016 - 16:00:08 CEST