What you need to know about bash functions
Bash, as a scripting language, can be a bit painful sometimes. It doesn't have good distinction between variable types, it has strange syntax for functions and the syntax for statements (such as if/while/case) is unintuitive and inconsistent. Having said that, you can rely on shell script being available on any Unix machine, and bash is almost as prevalent. Therefore, it's often the best choice for scripting.
You can get by with knowing the basic syntax, script parameters, variable assignment and command execution. However, knowing how to use functions will really boost your bash skills by a few levels. Here's everything you need to know to start using them straight away.
Syntax
Bash functions follow this format:
Or you can use the alternative syntax, which doesn't use the function
keyword, and includes parentheses:
Arguments/parameters
Functions act like miniature scripts. There's no way of declaring arguments in the function signature; they use the same $
prefixed variables that you use when collecting arguments to a script.
And a more advanced example:
Local variables
Thanks to Will Morton for suggesting this section.
You may have noticed that I used the keyword local
in one of the functions in one of the previous examples. This is because standard bash variables are global, as demonstrated here:
The local
keyword changes function variables to only apply to the current scope - global variables won't be overwritten:
Therefore, it's good practice to use the local
keyword in functions, to avoid unexpected behaviour.
Returning values
There is a return statement for bash functions, but the return must be a numeric value, to be consistent with all bash commands.
Returning a non-numeric value from a bash function is pretty tricky. The best way I've come across is to echo the value in the function, then to evaluate that function in the main script, like so:
You can also use backticks (``) to evaluate, instead of
$()`, but the latter is preferred.
Chaining
Functions behave like bash commands, which means that you can use &&
:
And you can use ||
to run something else in the case of a failure:
Miscellaneous behaviour
Exit statements exit the whole script:
You can therefore use functions as a "execute this or die" wrapper:
Summary
Hopefully there's something here that you can take away and apply to your bashing. If you have any more useful tips then feel free to leave a comment.