
Google's Shell Style Guide - shawndumas
http://google-styleguide.googlecode.com/svn/trunk/shell.xml
======
zobzu
"Indent 2 spaces. No tabs." Well fuck it.

Thats the only coding style that remotely makes sense to me:
[https://www.kernel.org/doc/Documentation/CodingStyle](https://www.kernel.org/doc/Documentation/CodingStyle)

While I'm at it, half the justifications Google gives for the shell guide are
inaccurate. Looks like a "overall people are used to this style so we're using
it and we'll try to justify it without knowing why"

This is a much better guide:

[http://devmanual.gentoo.org/tools-
reference/bash/](http://devmanual.gentoo.org/tools-reference/bash/)

Example: Gentoo's [[ ]] explanation actually makes sense.

~~~
nsmartt
I've always been conflicted on this. It's simply untrue that more than 3
levels of indentation indicates bad code. For example, HTML, XML, and JSON
often benefit from deeper levels of indentation.

Tabs have the benefit of having a dynamic size, so I could simply adjust the
tab width within my editor. Spaces also do not play as well with editors.
Unfortunately, browsers offer no means to change the width of tabs, so it's
impossible to properly display code using tabs. This is especially frustrating
when reading the source of a page indented using tabs. It would be much easier
to read with spaces, but not as easy to read as if I were able to set tab
width.

~~~
olau
On tabs vs. spaces, read the old classic: [http://www.jwz.org/doc/tabs-vs-
spaces.html](http://www.jwz.org/doc/tabs-vs-spaces.html)

tldr; don't use tabs.

I read that piece many years ago and thought who cares, but I've later changed
my editor to never use tabs. He's right.

Tabs are nice in theory, but in practice you end up with garbled code. It's
better to train yourself to get used to seeing code bases formatted slightly
differently, just one of the things you have to get over, IMHO. Like camel
notation version underscores versus dashes.

~~~
Shorel
Thanks for posting the original s-expr based, tab bashing article!

It has always been my own argument in favour of tabs:

\- The original argument against tabs was based on Lisp indentation rules.

\- Languages with very complex indentation rules like Lisp should use spaces.
There's no exception to this rule.

\- Languages from the C family should use Tabs, as Lisp indentation rules
don't apply to them.

\- Nowadays almost all popular languages can be considered to be part of the C
syntax family. Python and Lua are notable exceptions. PHP and Objective C
files should use tabs.

~~~
lispm
Never let get facts in your way.

[http://trac.common-lisp.net/mit-
cadr/browser/trunk/lisp/zwei...](http://trac.common-lisp.net/mit-
cadr/browser/trunk/lisp/zwei/indent.lisp)

MIT's Zmacs, the editor of the Lisp Machine indents with tabs.

~~~
Shorel
Good find, thanks.

However, one very old editor using tabs doesn't mean Lisp programmers actually
prefer them. It may even be the cause of tabs hate.

~~~
lispm
If the editor of the Lisp Machine, which was used by people like Steele,
Stallman, Pitman had no problems using tabs, it can't be that Lisp has a
technical requirement not to use tabs. Steele wrote a book about C. Stallman
wrote a Lisp in C and a C compiler...

Basically your arguments are from a strange parallel world.

------
js2
Re: long pipelines, the guide suggests:

    
    
      # Long commands
      command1 \
        | command2 \
        | command3 \
        | command4
    

However, by ending each line with the pipe the continuation is implicit and
the backslashes may be omitted:

    
    
      # Long commands
      command1 |
        command2 |
        command3 |
        command4

~~~
emmelaich
I usually use the trailing | but I can certainly see the sense in the leading
pipe.

It makes it clearer that the lines following are continuations; especially the
last in the pipeline.

~~~
sesqu
I consider the leading pipe clearer, and could be sold on it, but ending each
line with an inconvenient slash character (non-US layout) makes me strongly
favor the trailing version.

The trailing version seems more natural with operators like comma, but less
natural with operators like minus, and is far clearer with semicolonless
languages. I suspect if I were to go through old code, I'd find both uses, but
generally I prefer trailing.

The exception to this is languages like Haskell, though indentation could
serve the same purpose.

------
bcoates
I'm surprised there isn't more commentary on when and how to use external but
standard or common commands like grep, sed, awk, perl, join, find, tar,
parallel, etc.

It's one thing to use bash consistently everywhere but as a heavy multi-
machine shell user I've been bitten by incompatible or missing external
utilities more often than I care to admit. You might be surprised how many
systems aren't using the GNU utilities, have them running in a weird mode or
are using ancient versions of them.

Maybe Google is religious about keeping all their environments identical?

~~~
clarkm
And when you bring OS X into the picture, guaranteeing portability becomes a
nightmare, especially when it comes to scripts that have anything to do with
networking.

------
MichaelMoser123
I almost always use set -e with my bash scripts; this way you will always
notice if an invoked command failed or not; your script will not report that
everything is OK if part of the process actually failed.

[https://www.gnu.org/software/bash/manual/html_node/The-
Set-B...](https://www.gnu.org/software/bash/manual/html_node/The-Set-
Builtin.html#The-Set-Builtin)

Also: set -x is the best debugger in the world; really.

~~~
penguindev
Yeah, surprised that got no mention.

I thought the ./* wildcarding for safety was really cool. they also could have
covered find -print0 | xargs -0 for safety.

I'm glad they talked about "$@" being usually always the right thing to do.
That's been a hard won learning experience for me in the past...

------
rurounijones
"It should be possible for someone else to learn how to use your program or to
use a function in your library by reading the comments (and self-help, if
provided) without reading the code."

I know a few "Use the source, Luke" people who will rage at that.

~~~
nsmartt
The best argument I've seen here is that methods should be black boxes.
Comments should reveal the input, output, and side effects of a method. There
are two compelling reasons for this:

\- I can add to my own code, even if it's years old, without re-reading every
line every of every method I need

\- I can contribute to a code-base built by multiple people without reading
every line they've written

~~~
sounds
That is a particularly useful approach in functional languages, where the
function declaration itself is actually a fairly concrete guarantee of what
the function will do.

Shell scripts are almost the complete opposite end of the spectrum:

Shell script functions are usually only created as a last resort.

Global side effects (creating temporary files, changing global system state,
global variables, etc.) are what shell scripts are all about.

There are rare snippets of shell scripting that are different, using local
variables and doing some sort of calculation, but that is the exception, not
the rule.

While ideally comments would be prolific, poetic, and perfect, some commenting
is always better than none and most developers have bad habits of not
commenting their code, so pushing them gently in the direction of more, not
less, usually works.

~~~
sateesh
>> While ideally comments would be prolific ...

I would rather put that the comments should be succinct rather being prolific.
Better to put some explanation on tricky parts of the code as comments, and
have method/function/class behavior as javadoc, pod, pydoc etc.

~~~
sounds
You could have just said: "comments should be succinct" :)

------
emmelaich
The most important point:

    
    
        Shell should only be used for small
        utilities or simple wrapper scripts

------
thejosh
Rest of languages here: [https://code.google.com/p/google-
styleguide/source/browse/tr...](https://code.google.com/p/google-
styleguide/source/browse/trunk)

------
pirateking
Style guides are the worst to me. Taking some of the small joys left in
programming away, while making you feel like a cog at the same time.
Especially since many are outdated or just plain wrong, and very difficult to
change once established.

Tools that take the AST and output standardized code for peer review and
documentation sounds a little better. It would not deal well with the only
human problem really worth having a style guide for - naming things. But at
least humans aren't forced to jump through hoops. And the naming thing
possibly can be settled with an interface that asks something like - "what do
you want everyone to call the 'BitWarper' symbol?", for all named symbols.

But well written software is no place to express _individuality_ \- we just
want it to work and not make our eyes bleed when we have to fix it! Even
better then, just have machines generate and test all the code based on
systems of higher order rules and style guides in situations where factory
manufactured code is necessary. The outputs should be reasonable if the
requirements are well specified (NASA style). Humans can come in after and do
the real fun work in optimizing and finding clever hacks (if environment is
not mission critical and such liberty can be safely taken).

Having humans program character by character, with their bare hands, while
also suppressing creativity, is unnecessary in this Post-Industrial Age.

------
dredmorbius
Some things I don't particularly care for (2 space indent? SRSLY?!!), but it
warms the cockles of my heart to see an 80 character line limit.

Yes, it matters.

~~~
barrkel
An 80 character line limit almost mandates use of a 2 space indent, for most
languages.

Personally I prefer a line limit closer to 100, and 4 space indents in most
languages. Some languages end up with a lot more indenting than others owing
to structural literals and lambdas, and they benefit more from a smaller
indent.

~~~
abecedarius
I'm happy with 80 columns and 4 spaces in C, Python, etc. Don't see the
mandate. 2 spaces would make reading harder.

~~~
nfoz
I was surprised how quickly I got used to it. Occasionally I have to trace
blocks but not very often, and the tradeoff feels wonderful (it's much more
rare that I catch myself re-formatting things to avoid the 80char limit).

------
AYBABTME
Thanks for `go fmt`.

~~~
ushi
I had the exact same thought. The Go community is the only one (i know), where
such discussions are rare.

Write your code, run "go fmt", add, commit.

------
txutxu
I've seen many scripts wrapping steps inside a main() function and calling it
just after declaration.

If the justification is to localize variables which should be global, and
still will look like "global" to the rest of the program, it's ok.

But this is mainly used without sense, by personal tastes, and usually only
makes sense to the author and does not have any real benefice.

I prefer the concept "consistency is to not read unuseful steps", instead of
"add unuseful steps for consistency". That's how I think when I read code.

------
frozenport
Whats wrong with tabs?

~~~
jamesaguilar
Nothing that hasn't been said a billion times already -- and likewise for
spaces. A fairly comprehensive overview:
[http://c2.com/cgi/wiki?TabsVersusSpaces](http://c2.com/cgi/wiki?TabsVersusSpaces).
No, the clever people in this thread are not going to put the issue to bed for
once and for all.

~~~
skriticos2
I like how the golang team solved the issue. Ship a formatter in the core
package. Discussion closed.

~~~
Shorel
And, the formatter accepts a tabs option.

------
txutxu
Other one from the summaries:

I don't see how

    
    
        $((${X} + ${Y}))
    

... is more recommendable than ...

    
    
         $(( X + Y ))
    

for example.

But well, guide styles are a good thing, and this one can help to many people
"not used" to deal with shell scripts to follow some basics.

Edit: and help to people used to it, on working in a team.

------
rat87
Unfortunately firefox 24(on windows) has problems with rendering the style of
the xsl stylesheet and gives crap putput(Basically the full text content with
no line breaks). It seems to work on firefox 21/linux though. Also ie8/windows
and chrome 30/windows chromium 25/linux work.

------
rainhacker
Under the section 'When to use Shell', why does the style guide say 'If
performance matters, use something other than shell' ? I was under impression
that since shell script is low level it should have superior performance.

------
jebblue
i'm going to have to bookmark this site, I'm no Bash expert but with some Bash
and Java and a bit of Python here and there, sometimes I feel like I could
save the world.

------
andrewkreid
>> ...One example of this is Solaris SVR4 packages...

I wonder what Google are using Solaris for, and if it's just legacy stuff.

~~~
arethuza
Google appear to use Oracle Hyperion Financial Management for consolidated
reporting and planning (search their job pages - they usually have ads) - I
would suspect that this runs on Oracle boxes running Solaris.

------
eriksank
These rules look like they came from the low-intelligence paper belt. We do
not write rules like that. They must simply be part of the tool. Otherwise,
they do not count. What they now did, was to create an opportunity for someone
who knows that he is incompetent, to invent a new job for himself, that is,
"checking up" with his more competent colleagues, who contrary to him are
productive in writing code, on this style guide. Rule number one: Anybody who
wants to "enforce" this kind of rules must demonstrate that he is capable of
writing a parser that can apply them. It is simply bad practice to create that
kind of opportunities. It is bad practice to create that kind of jobs.
Therefore, this kind of documents must be rejected.

~~~
CraigJPerry
I think that's a bit harsh.

Of course we write style guides and while I like the idea that it's part of
the tool, that's rarely the case.

I don't follow the objection about a colleague helping ensure consistency
across a team. I'm really not sure why competence comes into that equation
either.

Agree with the idea any style guide should be automated. Several CI servers I
know of can incorporate style checkers and their reports into their workflow
so this can be made really hands off, even to the point of automatically
failing code review stage before its been lumped in the review queue.

Don't agree at all with the idea this type of doc should be rejected. In fact
it's completely wrong to jump into automation without having "found which way
is up" manually first time around.

------
hacker789
[http://google-
styleguide.googlecode.com/svn/trunk/shell.xml?...](http://google-
styleguide.googlecode.com/svn/trunk/shell.xml?showone=File_Extensions#File_Extensions)

 _> It is not necessary to know what language a program is written in when
executing it and shell doesn't require an extension so we prefer not to use
one for executables._

I disagree with their recommendation against using file extensions for
executables, and I'd love to have my mind changed about this.

Using an extension gives you automatic syntax highlighting. It also lets you
quickly glean the type of a file when exploring a directory for the first
time, which is more helpful than simply knowing whether the file can be
executed.

Why does a lack of necessity override those two benefits?

~~~
jfb
Any serious editor will read the #! line for syntax highlighting, which has
the benefit of being much more likely to be correct than the user visible and
modifiable file name.

~~~
raverbashing
Except when it doesn't have that line because it's a C/C+header file.

And then the editor doesn't know what to do with that header file without
extension. Yes, if you see some Google C++ code they do that

Really, horrible practice.

~~~
kondro
What are you doing making C header files executable?

~~~
raverbashing
Where did I say I was making it executable?

~~~
kondro
They were only advocating no extension for executable shell files, not all
files.

~~~
raverbashing
Yes, I remembered seeing a C++ google product without the .h extension in
header files (or other similar extensions)

But apparently they stopped this nonsense

~~~
ithkuil
It's not google, it's C++ convention.

[http://stackoverflow.com/questions/301586/what-is-the-
differ...](http://stackoverflow.com/questions/301586/what-is-the-difference-
between-using-includefilename-and-includefilename-h)

Btw, many editors understand // - _\- C++ -_ -

Nevertheless Google's c++ style guide ([https://code.google.com/p/google-
styleguide/source/browse/tr...](https://code.google.com/p/google-
styleguide/source/browse/trunk/cppguide.xml)) in fact says that headers should
have the .h suffix.

~~~
raverbashing
Ah thanks for pointing that out

> Btw, many editors understand // \-- C++ --

Maybe, but if I vim /usr/include/c++/4.2.1/iostream doesn't work (only if I
set it manually)

