71

Java community use 4 spaces as the unit of indentation. 1
Ruby community use 2 spaces that is generally agreed-upon. 2

What's the standard for indentation in shell scripts? 2 or 4 spaces or 1 tab?

7
  • 50
    Standards are great. We've got so many of them to choose from...
    – Shadur
    May 23 '12 at 9:39
  • 1
    For the funny, take a look at the "standard" indention for the scripts in /etc/init.d. You will find the two-spaces standard, four-spaces, one-tab, etc., used in different scripts, sometimes a couple of those standards in the same script.
    – cjc
    May 23 '12 at 10:52
  • 1
    shameless plug: let bash itself decide of the proper indentation automagically: unix.stackexchange.com/questions/274888/… Apr 7 '16 at 12:40
  • 1
    The standard is to eschew tab characters and slap anyone who fails to follow that simple rule. The number of spaces you use instead is your business, but if you choose to follow the Path of Tab then there is no helping you. Apr 7 '16 at 14:47
  • 7
    If you use tabs, you can indent your <<- heredocs. stackoverflow.com/a/33817423/99777 You cannot do that with spaces. "For shell scripts, using tabs is not a matter of preference or style; it's how the language is defined." Mar 18 '19 at 2:28
55

There is no standard indentation in shell scripts that matters.

Slightly less flippant answer:

  • Pick a standard in your team that you can all work to, to simplify things.
  • Use something your editor makes easy so you don't have to fight to stick to the standard.
1
  • 2
    Historically four spaces per indentation level might arguably the most common.
    – con-f-use
    Nov 20 '15 at 22:22
29

I've never encountered shell specified style guide but for bash programming this is the most popular one:

Bash Style Guide and Coding Standard.pdf | lug.fh-swf.de

The indentation of program constructions has to agree with the logic nesting depth. The indentation of one step usually is in line with the tabulator steps of the editor selected. In most cases 2, 4 or 8 are chosen.

1
  • The guide states either "2, 4 or 8 are chosen" but implies 2 spaces from the examples.
    – Matt Clegg
    Jun 3 '20 at 12:20
22

The Google Style Guide says 2 spaces

https://google.github.io/styleguide/shell.xml#Indentation

Agree with others that it is an arbitrary choice.

Its source code is hosted at: https://github.com/google/styleguide

-6

Just open the file with vim editor and typing gg=G will reindent the entire file. I think this is the standard.

1
  • 4
    That will indent based on the value of the shiftwidth (aka sw) vim variable. By default, it's 8 which corresponds to the default tab stop in terminals. That value is historical, few people use 8 space indentation nowadays, I've had set sw=2 in my ~/.vimrc for decades. Apr 15 '18 at 9:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.