Have you actually run the code? Both snippets return fun: command not found and this is the problem you need to address first.
Unless you managed to export fun as a function, or defined it elsewhere in a way that allows the inner bash to recognize the command (I will not elaborate). This situation would be quite misleading, thus unfortunate in the context of further issues.
Let's start with straightforward code that does what you probably wanted:
#!/bin/bash
fun ()
{
echo "$1"
}
for i in {1..5}
do
fun "$i" &
done
If you get numbers not in sequence, it's because of &. I used & here because it was in your original code.
Your definition of the function is syntactically OK. My definition uses $1 instead of $0, we'll get to it. To use a function you just call its name, with or without arguments. In our case:
fun
fun arg1
fun arg1 arg2
Inside a function $1, $2, … expand to respective arguments. You use $@ (or $* if you know what you are doing) to get all the arguments. You use $# to get the number of arguments. This is very similar to a situation where fun is a shell script.
$0 inside a function is $0 of the main shell. It has nothing to do with arguments passed to the function.
You can run the function in a subshell:
( fun arg1 )
or in the background (which implicitly runs it in a subshell as well):
fun arg1 &
If fun is a function in the main shell then these subshells will also know what to do when the command is fun. On the other hand a shell started with bash -c has no idea of fun.
Again: unless you managed to export … or …
In your case bash -c is rather an obstacle. I see no point in using it. It is possible to make it work but it would be cumbersome. Still, your explicit question is:
can we pass multiple parameters to function by using bash -c?
We can. Cumbersome example below. Note the function is slightly different (for educational reason). I also dropped & because it only obfuscates the results.
#!/bin/bash
fun ()
{
echo "$2"
}
export -f fun
var="string"
for i in {1..5}
do
bash -c 'fun "$2" "$1"' inner-bash "$i" "$var"
done
Exporting a function from Bash to Bash is possible and we just did it. Exporting a function from Bash to another shell is impossible, unless the shell tries to be compatible and deliberately interprets some environment variables as functions.
fun "$2" "$1" is single-quoted, so in the main shell "$2" and "$1" are not expanded (being single-quoted, they are not double-quoted). In the context of the inner bash these $2 and $1 are double-quoted and they expand to parameters provided after inner-bash (which is an arbitrary name here).
See what happens to a number stored as $i:
- it's
$i in the context of the main shell;
- then it's
$1 in the context of the inner shell;
- then it's
$2 in the context of the function in the inner shell.
There is no advantage of using bash -c here, only inconvenience. Do not complicate your code this way.
One more thing: double-quote variables.