I am trying to search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line.
I would like to pass parameters within my script. I tried:
myBackupFunction("..", "...", "xx")
function myBackupFunction($directory, $options, $rootPassword) {
...
}
But the syntax is not correct, how to pass a parameter to my function?
If you prefer named parameters, it's possible (with a few tricks) to actually pass named parameters to functions (also makes it possible to pass arrays and references).
The method I developed allows you to define named parameters passed to a function like this:
You can also annotate arguments as @required or @readonly, create ...rest arguments, create arrays from sequential arguments (using e.g.
string[4]
) and optionally list the arguments in multiple lines:In other words, not only you can call your parameters by their names (which makes up for a more readable core), you can actually pass arrays (and references to variables - this feature works only in bash 4.3 though)! Plus, the mapped variables are all in the local scope, just as $1 (and others).
The code that makes this work is pretty light and works both in bash 3 and bash 4 (these are the only versions I've tested it with). If you're interested in more tricks like this that make developing with bash much nicer and easier, you can take a look at my Bash Infinity Framework, the code below is available as one of its functionalities.
I hope this example can help you. It takes two numbers from the user, feeds them to the function called
add
(in the very last line of the code), andadd
will sum them up and print them.Knowledge of high level programming languages (C/C++/Java/PHP/Python/Perl ...) would suggest to the layman that bash functions should work like they do in those other languages. Instead, bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (ls -l). In effect, function arguments in bash are treated as positional parameters (
$1, $2..$9, ${10}, ${11}
, and so on). This is no surprise considering howgetopts
works. Parentheses are not required to call a function in bash.(Note: I happen to be working on Open Solaris at the moment.)
A simple example that will clear both during executing script or inside script while calling a function.
Miss out the parens and commas:
and the function should look like this:
Thought I'd pipe in with mention of another way to pass named parameters to bash... passing by reference. This is supported as of bash 4.0
An alternative syntax for bash 4.3 is using a nameref
Although the nameref is a lot more convenient in that it seamlessly dereferences, some older supported distros still ship an older version so I won't recommend it quite yet.