8

Does the Bash language have a standard that dictates whether comments about the function should precede the function or be placed inside of it. I have seen scripts written both ways.

# Comment preceding function.
func1(){
echo "example"
}

-or-

func2() {
# Comment inside of function
echo "example"
}
Sco
  • 115
  • 2
  • 6
  • 2
    There was a question here recently about encoding comments inside functions as `:` statements so that the functions could be self-documenting even under `declare` – Jeff Schaller Jul 11 '16 at 23:28
  • Found it: http://unix.stackexchange.com/q/295022/117549 – Jeff Schaller Jul 11 '16 at 23:51
  • 1
    one common method is that comments ABOUT the function belong outside it, while comments DOCUMENTING (e.g. input and output) it belong inside. – cas Jul 12 '16 at 14:10
  • 1
    The admin that closed this important topic could have put in some information that was useful before doing so IMO. – Mike Q Mar 19 '20 at 13:42

2 Answers2

6

In most programming languages, the comments that describe what the function does go before the function. You should probably do the same for bash. You should also use indentation:

# function 1 comment
func1() {
    echo "example"
}
Edward Falk
  • 1,913
  • 15
  • 14
3

The examples from the official bash repo comment before the function header and so does https://github.com/scop/bash-completion.

I don't think it matters much as long as it stays super easy to decipher for the person who'll be refactoring it 6 months from now (which might be you).

Here's another way to comment in shells:

:<<'DOC'
My 
multi 
line
comment
DOC

Indentation and consistency are generally nice to have too.

Petr Skocik
  • 28,176
  • 14
  • 81
  • 141