When working out a bash script there are some times situations in which I find myself repeating the same bash code over and over again in a script. So there should be a way to define a block of bash script code as part of a function that will take one or more arguments, and then just call that function over and over again rather than repeating the whole block of code.
So in this post I will be going over some of the basics of functions when writing bash scripts.
Lets start with the very basics of bash functions. I can define one by typing a name for a function, followed by and opening and closing set of parentheses after which I will be placing what I want the function to be inside a set of curly brackets.
Once I have my function worked out I can call it any number of times that I want in the body of a script.
So once I have my bash script together in an editor I can save it as something like func_basic.sh. I can then call it with bash or make the script executable with chmod and run it directly because of the bash shebang at the top of the file.
So now we have the basic idea of a function in bash. However maybe there is a few more things to cover when it comes to functions in bash scripts. There is the question of arguments, how to return something, and other function related topics. So maybe at least a few more examples are called for before moving on to some other bash script related topics.
So now about arguments with bash functions. Each bash function has its own set of positioned arguments just like that of the main script file. When I do to call the function I just need to pass the values that I want for $1 $2 and so forth.
The best way to go about defining a return value might be to just echo out the return value as ways just use $() as a way to call it.
Now for a more complex example of bash functions that has to do with making a few math functions with bash. It might be better to make use of a command that will tap into another language such as node, or awk, when it comes to doing some actually programing. However it is possible to do some basics with bash itself at least.
So now I have a little javaScirpt that I can use with node.
Just like bash scripts I can make the script executable because I placed the nodejs shebang at the top of the file.
Looks like my eval method works for what it is worth also.
So functions in bash are yet another feature in bash that one should become familiar with to learn how to read and write bash scripts. They ming be a bit lacking compared to what I am useful in other languages, but the basic features that I would expect in an environment such as bash are there.