nhed
nhed

Reputation: 5999

Bash style: indent function defined with conditional?

if one was to have a conditional control which version of a function is defined (rather than have the conditional in the function)

is there a universal agreement weather the functions should be indented?

if whatever; then
function myfunc() {
  echo "impl 1"
}
else
function myfunc() {
  echo "impl 2"
}
fi

vs

if whatever; then
  function myfunc() {
    echo "impl 1"
  }
else
  function myfunc() {
    echo "impl 2"
  }
fi

(only answer the question of indentation not on use of the keyword function, location of braces etc)

Upvotes: 1

Views: 201

Answers (1)

chepner
chepner

Reputation: 531918

As a matter of opinion: yes, indent it.

As a more objective statement (and one that I am more comformable claiming to be a universal opinion): use the same indentation (or lack thereof) as you would use with any other statement in the body of a conditional. That is, write

if whatever; then
  function foo {
    ...
  }
fi

if whatever; then
  foo=3
fi

or

if whatever; then
function foo {
    ...
}
fi

if whatever; then
foo=3
fi

The rationale for this is that syntax aside, a function definition is just an assignment. Instead of assigning a string to a parameter name, it binds a compound command. In fact, even after the changes made after the ShellShock exploit was discovered, it is still possible to dynamically define a function in bash via an environment variable (mimicking the way bash itself exports a function defined the normal way):

$ env "BASH_FUNC_foo%%=() { echo 1; }" bash
$ foo
1

As such, there is little reason to treat it differently than any other assignment statement as far as indentation is concerned.

Upvotes: 1

Related Questions