I'm quite new on the shell scripting front and was wondering whether it is is possible to call a function which itself than calls another function with none, one or multiple arguments. The first argument would be the name of the function to call, every other argument is an argument for the function to call.
As a background, I want to write a shell script to use some built-in OpenFOAM functions, namely runParallel
and runApplication
, which, for clarification, I called runSerial
in the example above. Those functions do different things, as the name suggests they run a command in either serial or parallel mode.
A simulation in OpenFOAM is made up of multiple function calls and all I want to do is shorten the code so that instead of this
#!/bin/sh
# $n_core is a user input how many cores to use
printf 'On how many cores do you want to run the simulation?'
read -r n_core
if [ $n_core -eq "1" ]; then
runSerial "functionOne" # no arguments here
runSerial "functionTwo" "arg1"
runSerial "functionThree" "arg1" "arg2"
...
else
runParallel "functionOne" # no arguments here
runParallel "functionTwo" "arg1"
runParallel "functionThree" "arg1" "arg2"
...
fi
I was wondering whether I could replace that with something like this
#!/bin/sh
runSerialOrParallel()
{
if [ $n_core -eq "1" ]; then
runSerial "$1" "$2" ...
else
runParallel "$1" "$2" ...
fi
}
# $n_core is a user input how many cores to use
printf 'On how many cores do you want to run the simulation?'
read -r n_core
runSerialOrParallel "functionOne" # no arguments here
runSerialOrParallel "functionTwo" "arg1"
runSerialOrParallel "functionThree" "arg1" "arg2"
At the moment I'm stuck with the question on how to account for the arguments for the function which my runSerialOrParallel
function should call itself. So if I want functionTwo
to be run in either serial or parallel, with one argument for functionTwo
itself, how do I make that happen inside runSerialOrParallel
?
Any help would be greatly appreciated and please forgive me if there is a profane answer to that question which I could easily have found myself but didn't.
cheers!
(I hope the edit cleared some things up, my bad ..)
zsh
differs frombash
, that's why you're using it. Readman zsh
orman bash
about theshift
builtinzsh
here as that script has a/bin/sh
shebang, but if you want a function to pass its arguments to some other command, whether the shell issh
(Bourne or POSIX),bash
orzsh
, the syntax is "$@"`.runSerialOrParallel
function e.g. it should sayrunSerial "$1" "$@"
? I want the script to run in eiherzsh
orbash
or anything else, that is why I'm using the shebang and that is why I thought it shouldn't make a difference here @waltinator. I know there are a lot of differences, but I will have a look inside theshift
command, thank you!