56

At work, I write bash scripts frequently. My supervisor has suggested that the entire script be broken into functions, similar to the following example:

#!/bin/bash

# Configure variables
declare_variables() {
    noun=geese
    count=three
}

# Announce something
i_am_foo() {
    echo "I am foo"
    sleep 0.5
    echo "hear me roar!"
}

# Tell a joke
walk_into_bar() {
    echo "So these ${count} ${noun} walk into a bar..."
}

# Emulate a pendulum clock for a bit
do_baz() {
    for i in {1..6}; do
        expr $i % 2 >/dev/null && echo "tick" || echo "tock"
        sleep 1
    done
}

# Establish run order
main() {
    declare_variables
    i_am_foo
    walk_into_bar
    do_baz
}

main

Is there any reason to do this other than "readability", which I think could be equally well established with a few more comments and some line spacing?

Does it make the script run more efficiently (I would actually expect the opposite, if anything), or does it make it easier to modify the code beyond the aforementioned readability potential? Or is it really just a stylistic preference?

Please note that although the script doesn't demonstrate it well, the "run order" of the functions in our actual scripts tends to be very linear -- walk_into_bar depends on stuff that i_am_foo has done, and do_baz acts on stuff set up by walk_into_bar -- so being able to arbitrarily swap the run order isn't something we would generally be doing. For example, you wouldn't suddenly want to put declare_variables after walk_into_bar, that would break things.

An example of how I would write the above script would be:

#!/bin/bash

# Configure variables
noun=geese
count=three

# Announce something
echo "I am foo"
sleep 0.5
echo "hear me roar!"

# Tell a joke
echo "So these ${count} ${noun} walk into a bar..."

# Emulate a pendulum clock for a bit
for i in {1..6}; do
    expr $i % 2 >/dev/null && echo "tick" || echo "tock"
    sleep 1
done
  • 30
    I like your boss. In my scripts I also put main() at the top and add main "$@" at the bottom to call it. That lets you see the high level script logic first thing when you open it. – John Kugelman Sep 29 '16 at 22:36
  • 22
    I disagree with the notion that readability can "be equally well established with a few more comments and some line spacing." Except maybe for fiction, I wouldn't want to deal with a book that doesn't have a table of contents and descriptive names for each chapter and section. In programming languages, that's the kind of readability that functions can provide, and comment's can't. – Rhymoid Sep 30 '16 at 7:55
  • 6
    Note that variables declared in functions should be declared local - this provides variable scope which is incredibly important in any non-trivial script. – Boris the Spider Sep 30 '16 at 9:38
  • 7
    I disagree with your boss. If you have to break down your script into functions, you probably shouldn't write a shell script in the first place. Write a program instead. – el.pescado Sep 30 '16 at 10:28
  • 5
    Functions are for processes that are repeated, either within the script or in more than one script. They also allow uniform methodologies to be put into place. E.g using a function to write to syslog. As long as everyone uses the same function, your syslog entries are more consistent. Single use functions like your example needlessly complicate the script. In some cases, they introduce issues (variable scoping). – Xalorous Sep 30 '16 at 11:48

11 Answers 11

37

I've started using this same style of bash programming after reading Kfir Lavi's blog post "Defensive Bash Programming". He gives quite a few good reasons, but personally I find these the most important:

  • procedures become descriptive: it's much easier to figure out what a particular part of code is supposed to do. Instead of wall of code, you see "Oh, the find_log_errors function reads that log file for errors ". Compare it with finding whole lot of awk/grep/sed lines that use god knows what type of regex in the middle of a lengthy script - you've no idea what's it doing there unless there's comments.

  • you can debug functions by enclosing into set -x and set +x. Once you know the rest of the code works alright , you can use this trick to focus on debugging only that specific function. Sure, you can enclose parts of script, but what if it's a lengthy portion ? It's easier to do something like this:

     set -x
     parse_process_list
     set +x
    
  • printing usage with cat <<- EOF . . . EOF. I've used it quite a few times to make my code much more professional. In addition, parse_args() with getopts function is quite convenient. Again, this helps with readability, instead of shoving everything into script as giant wall of text. It's also convenient to reuse these.

And obviously, this is much more readable for someone who knows C or Java, or Vala, but has limited bash experience. As far as efficiency goes, there's not a lot of what you can do - bash itself isn't the most efficient language and people prefer perl and python when it comes to speed and efficiency. However, you can nice a function:

nice -10 resource_hungry_function

Compared to calling nice on each and every line of code, this decreases whole lot of typing AND can be conveniently used when you want only a part of your script to run with lower priority.

Running functions in background, in my opinion, also helps when you want to have whole bunch of statements to run in background.

Some of the examples where I've used this style:

  • 2
    I am not sure you should take any suggestions from that article very seriously. Granted, it has a few good ideas, but it is clearly not someone used to shell scripting. Not a single variable in any of the examples is quoted(!) and it suggests using UPPER CASE variable names which is often a very bad idea since they can conflict with existing env vars. Your points in this answer make sense, but the linked article seems to have been written by someone who is just used to other languages and is trying to force their style onto bash. – terdon Feb 10 '17 at 9:43
  • 1
    @terdon I went back to the article and re-read it. The only place where author mentions upper case variable naming is in "Immutable Global Variables". If you consider global variables as those that have to be within function's environment, then it makes sense to make them capital. On side note, bash's manual doesn't state convention for variable case. Even here accepted answer says "usually" and the only "standard" is by Google, which doesn't represent whole IT industry. – Sergiy Kolodyazhnyy Feb 10 '17 at 16:07
  • @terdon on another note, I do agree 100% that variable quoting should have been mentioned in the article, and it has been pointed out in the comments on the blog,too. Also, I wouldn't judge someone using this style of coding, regardless of whether or not they're used to another language. This whole question and answers clearly show there's advantages to it, and person's degree to which they're used to another language is probably irrelevant here. – Sergiy Kolodyazhnyy Feb 10 '17 at 16:10
  • 1
    @terdon well, the article was posted as part of the "source" material. I could have posted everything as my own opinions, but I just had to give credit that some of the stuff I learned from the article, and that all this came from researching over time. The author's linkedin page shows they have good experience with Linux and IT in general, so I'd guess the article doesn't really show that, but I trust in your experience when it comes to Linux and shell scripting, so you might be right. – Sergiy Kolodyazhnyy Feb 10 '17 at 16:34
  • 1
    That's an excellent answer but I'd also like to add that variable scope in Bash is funky. For that reason, I prefer to declare my variables inside functions using local and calling everything via the main() function. This makes things a lot more manageable and you can avoid a potentially messy situation. – Housni Sep 14 '18 at 11:23
65

Readability is one thing. But there is more to modularisation than just this. (Semi-modularisation is maybe more correct for functions.)

In functions you can keep some variables local, which increases reliability, decreasing the chance of things getting messed up.

Another pro of functions is re-usability. Once a function is coded, it can be applied multiple times in the script. You can also port it to another script.

Your code now may be linear, but in the future you may enter the realm of multi-threading, or multi-processing in the Bash world. Once you learn to do things in functions, you will be well equipped for the step into the parallel.

One more point to add. As Etsitpab Nioliv notices in the comment below, it's easy to redirect from functions as a coherent entity. But there's one more aspect of redirections with functions. Namely, the redirections can be set along the function definition. Eg.:

f () { echo something; } > log

Now no explicit redirections are needed by the function calls.

$ f

This may spare many repetitions, which again increases reliability and helps keeping things in order.

See also

  • 55
    Very good answer although it would be much better if it were broken into functions. – Pierre Arlaud Sep 30 '16 at 11:40
  • 1
    Maybe add that functions allow you to import that script into another script (by using source or . scriptname.sh, and use those functions as-if they were in your new script. – SnakeDoc Sep 30 '16 at 21:37
  • That's already covered in another answer. – Tomasz Sep 30 '16 at 21:40
  • 1
    I appreciate that. But I'd rather let other people be important as well. – Tomasz Sep 30 '16 at 22:00
  • 7
    I faced a case today where I had to redirect some of the output of a script to a file (to sent it via email) instead of echoing. I simply had to do myFunction >> myFile to redirect the output of the desired functions. Pretty convenient. Might be relevant. – Etsitpab Nioliv Sep 30 '16 at 23:28
39

In my comment, I mentioned three advantages of functions:

  1. They are easier to test and verify correctness.

  2. Functions can be easily reused (sourced) in future scripts

  3. Your boss likes them.

And, never underestimate the importance of number 3.

I would like to address one more issue:

... so being able to arbitrarily swap the run order isn't something we would generally be doing. For example, you wouldn't suddenly want to put declare_variables after walk_into_bar, that would break things.

To get the benefit of breaking code into functions, one should try to make the functions as independent as possible. If walk_into_bar requires a variable that is not used elsewhere, then that variable should be defined in and made local to walk_into_bar. The process of separating the code into functions and minimizing their inter-dependencies should make the code clearer and simpler.

Ideally, functions should be easy to test individually. If, because of interactions, they are not easy to test, then that is a sign that they might benefit from refactoring.

  • I'd argue that it's sometimes sensible to model and enforce those dependencies, vs refactoring to avoid them (since if there are enough of them, and they're sufficiently hairy, that can just lead to a case where things are no longer modularized into functions at all). A very complicated use case once inspired a framework to do just that. – Charles Duffy Sep 29 '16 at 23:42
  • 4
    What needs to be divided into functions should be, but the example takes it too far. I think the only one that really bugs me is the variable declaration function. Global variables, especially static ones, should be defined globally in a commented section dedicated to that purpose. Dynamic variables should be local to the functions that use and modify them. – Xalorous Sep 30 '16 at 11:52
  • @Xalorous I've seen a practices where global variables are Initialized in a procedure, as an intermediate and quick step before the developing of a procedure that reads their value from an external file... I agree it should be cleaner to separate definition and initialization but seldom you have to bend to undergo to the advantage number 3 ;-) – Hastur Oct 3 '16 at 7:50
13

You break the code into functions for the same reason you would do that for C/C++, python, perl, ruby or whatever programming language code. The deeper reason is abstraction - you encapsulate lower level tasks into higher level primitives (functions) so that you don't need to bother about how things are done. At the same time, the code becomes more readable (and maintainable), and the program logic becomes more clear.

However, looking at your code, I find it quite odd to have a function to declare variables; this really makes me rise an eye brow.

  • Underrated answer IMHO. Do you suggest to declare the variables in the main function/method, then? – David Tabernero M. Jun 18 '18 at 17:12
12

While I totally agree with the reusability, readability, and delicately kissing the bosses but there is one other advantage of functions in : variable scope. As LDP shows:

#!/bin/bash
# ex62.sh: Global and local variables inside a function.

func ()
{
  local loc_var=23       # Declared as local variable.
  echo                   # Uses the 'local' builtin.
  echo "\"loc_var\" in function = $loc_var"
  global_var=999         # Not declared as local.
                         # Therefore, defaults to global. 
  echo "\"global_var\" in function = $global_var"
}  

func

# Now, to see if local variable "loc_var" exists outside the function.

echo
echo "\"loc_var\" outside function = $loc_var"
                                      # $loc_var outside function = 
                                      # No, $loc_var not visible globally.
echo "\"global_var\" outside function = $global_var"
                                      # $global_var outside function = 999
                                      # $global_var is visible globally.
echo                      

exit 0
#  In contrast to C, a Bash variable declared inside a function
#+ is local ONLY if declared as such.

I don't see this very often in real world shell scripts, but it seems like a good idea for more complex scripts. Reducing cohesion helps avoid bugs where you're clobbering a variable expected in another part of the code.

Reusability often means creating a common library of functions and sourceing that library into all of your scripts. This won't help them run faster, but it will help you write them faster.

  • Few people are explicitly using local, but I think most people writing scripts broken up into functions still follow the design principle. Usign local just makes it harder to introduce bugs. – Voo Oct 1 '16 at 13:56
  • local makes variables available to function and its children, so it's really nice to have a variable that can be passed down from function A , but unavailable to function B, which may want to have variable with same name but different purpose. So that's good for defining the scope, and as Voo said - less bugs – Sergiy Kolodyazhnyy Oct 8 '16 at 1:06
10

A completely different reason from those already given in other answers: one reason this technique is sometimes used, where the sole non-function-definition statement at top-level is a call to main, is to make sure the script does not accidentally do anything nasty if the script is truncated. The script may be truncated if it is piped from process A to process B (the shell), and process A terminates for whatever reason before it has finished writing the whole script. This is especially likely to happen if process A fetches the script from a remote resource. While for security reasons that is not a good idea, it is something that is done, and some scripts have been modified to anticipate the problem.

  • 5
    Interesting! But I find it troubling that one has to take care of those things in each of the programs. On the other hand, exactly this main() pattern is usual in Python where one uses if __name__ == '__main__': main() at the end of the file. – Martin Ueding Sep 30 '16 at 14:25
  • 1
    The python idiom has the advantage of letting other scripts import the current script without running main. I suppose a similar guard could be put in a bash script. – Jake Cobb Oct 3 '16 at 14:15
  • @Jake Cobb Yes. I now do that in all new bash scripts. I have a script that contains a core infrastructure of functions used by all new scripts. That script can be sourced or executed. If sourced, its main function is not executed. Detection of source vs execution is via the fact that the BASH_SOURCE contains the name of the executing script. If it's the same as the the core script, the script is being executed. Otherwise, it's being sourced. – DocSalvager Oct 5 '16 at 8:10
7

A process requires a sequence. Most tasks are sequential. It makes no sense to mess with the order.

But the super big thing about programming - which includes scripting - is testing. Testing, testing, testing. What test scripts do you currently have to validate the correctness of your scripts?

Your boss is trying to guide you from being a script kiddy to being a programmer. This is a good direction to go in. People who come after you will like you.

BUT. Always remember your process-oriented roots. If it makes sense to have the functions ordered in the sequence in which they are typically executed, then do that, at least as a first pass.

Later, you will come to see that some of your functions are handling input, others output, others processing, others modelling data, and others manipulating the data, so it may be smart to group similar methods, perhaps even moving them off into separate files.

Later still, you may come to realize you've now written libraries of little helper functions that you use in many of your scripts.

6

Comments and spacing can not get anywhere near the readability that functions can, as I will demonstrate. Without functions, you can't see the forest for the trees - big problems hide among many lines of detail. In other words, people can't simultaneously focus on the fine details and on the big picture. That might not be obvious in a short script; so long as it remains short it may be readable enough. Software gets bigger, though, not smaller, and certainly it's part of the entire software system of your company, which is surely very much larger, probably millions of lines.

Consider if I gave you instructions such as this:

Place your hands on your desk.
Tense your arm muscles.
Extend your knee and hip joints.
Relax your arms.
Move your arms backwards.
Move your left leg backwards.
Move your right leg backwards.
(continue for 10,000 more lines)

By the time you got halfway through, or even 5% through, you would have forgotten what the first several steps were. You couldn't possibly spot most problems, because you couldn't see the forest for the trees. Compare with functions:

stand_up();
walk_to(break_room);
pour(coffee);
walk_to(office);

That's certainly much more understandable, no matter how many comments you might put in the line-by-line sequential version. It also makes it far more likely you'll notice that you forgot to make the coffee, and probably forgot sit_down() at the end. When your mind is thinking of the details of grep and awk regexes, you can't be thinking big picture - "what if there is no coffee made"?

Functions primarily allow you to see the big picture, and notice that you forgot to make the coffee (or that someone might prefer tea). At another time, in a different frame of mind, you worry about the detailed implementation.

There are also other benefits discussed in other answers, of course. Another benefit not clearly stated in the other answers is that functions provide a guarantee that's important in preventing and fixing bugs. If you discover that some variable $foo in the proper function walk_to() was wrong, you know that you only have to look at the other 6 lines of that function to find everything that could have been affected by that problem, and everything that could have caused it to be wrong. Without (proper) functions, anything and everything in the whole system might be a cause of $foo being incorrect, and anything and everything might be affected by $foo. Therefore you can't safely fix $foo without re-examining every single line of the program. If $foo is local to a function, you can guarantee any changes are safe and correct by checking only that function.

  • 1
    This isn't bash syntax. It's a shame though; I don't think there is a way to pass input to functions like that. (i.e. pour(); < coffee). It looks more like c++ or php (I think). – tjt263 Oct 3 '16 at 10:13
  • 2
    @tjt263 without the parentheses, it's bash syntax: pour coffee. With parens, it's pretty much every other language. :) – Ray Morris Oct 4 '16 at 4:57
5

Some relevant truisms about programming:

  • Your program will change, even if your boss insists this is not the case.
  • Only code and input affect the behavior of the program.
  • Naming is difficult.

Comments start out as a stop-gap for not being able to express your ideas clearly in code*, and get worse (or simply wrong) with change. Therefore, if at all possible, express concepts, structures, reasoning, semantics, flow, error handling and anything else pertinent to the understanding of the code as code.

That said, Bash functions have some issues not found in most languages:

  • Namespacing is terrible in Bash. For example, forgetting to use the local keyword results in polluting the global namespace.
  • Using local foo="$(bar)" results in losing the exit code of bar.
  • There are no named parameters, so you have to keep in mind what "$@" means in different contexts.

* I'm sorry if this offends, but after using comments for some years and developing without them** for more years it's pretty clear which is superior.

** Using comments for licensing, API documentation and the like is still necessary.

  • I set almost all local variables by declaring them to null at the beginning of the function... local foo="" Then setting them using command execution to act on the result... foo="$(bar)" || { echo "bar() failed"; return 1; }. This gets us out of the function quickly when a required value cannot be set. The curly braces are necessary to insure that the return 1 is only executed on failure. – DocSalvager Oct 1 '16 at 23:25
5

Time is money

There are other good answers that spread light on the technical reasons to write modularly a script, potentially long, developed in a working environment, developed to be used by a group of persons and not only for your own use.

I want to focus on one expect: in a working environment "time is money". So the absence of bugs and the performances of your code are evaluated together with readibility, testability, maintainability, refactorability, reusability...

Writing in "modules" a code will decrease the reading time needed not only by the coder itself, but even the time used by the testers or by the boss. Moreover note that the time of a boss is usually paid more then the time of a coder and that your boss will evaluate the quality of your job.

Furthermore writing in independent "modules" a code (even a bash script) will allow you to work in "parallel" with other component of your team shortening the overall production time and using at best the single's expertise, to review or rewrite a part with no side effect on the others, to recycle the code you have just written "as is" for another program/script, to create libraries (or libraries of snippets), to reduce the overall size and the related likelihood of errors, to debug and test thorough each single part... and of course it will organize in logical section your program/script and enhance its readability. All things that will save time and so money. The drawback is that you have to stick to standards and comment your functions (that you have nonetheless to do in a working environment).

To adhere to a standard will slow down your work in the beginning but it will speed up the work of all the others (and your too) afterwards. Indeed when the collaboration grows in number of people involved this becomes an unavoidable need. So, for example, even if I believe that the global variables have to be defined globally and not in a function, I can understand a standard that inizializes them in a function named declare_variables() called always in the first line of the main() one...

Last but not least, do not underestimate the possibility in modern source code editors to show or to hide selectively separate routines (Code folding). This will keep compact the code and focused the user saving again time.

enter image description here

Here above you can see how it is unfolded only the walk_into_bar() function. Even of the other ones were 1000 lines long each, you could still keep under control all the code in a single page. Note it is folded even the section where you go to declare/initialize the variables.

1

Aside from the reasons given in other answers:

  1. Psychology: A programmer whose productivity is being measured in lines of code will have an incentive to write unnecessarily verbose code. The more management is focusing on lines of code, the more incentive the programmer has to expand his code with unneeded complexity. This is undesirable since increased complexity can lead to increased cost of maintenance and increased effort required for bug fixing.
  • It is not so bad answer, as the downvotes say. Note: agc says, also this is a possibility, and yes, it is. He doesn't say it would be the only possibility, and doesn't accuse anybody, only states the facts. Although I think today is nearly unheard a direct "code line" --> "$$" style contract job, on indirect means it is quite common, that yes, the mass of the produced code counts by the leaders/bosses. – peterh Oct 1 '16 at 19:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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