Operating System - Linux
1758264 Members
2693 Online
108868 Solutions
New Discussion юеВ

pass function as an argument

 
SOLVED
Go to solution
Gemini_2
Regular Advisor

pass function as an argument

I have 4 functions, I want to know if I can consolidate to 3 by passing the funtion as an argument.

function f1 {
}

function f2 {
}

function f3 {
for i in $files
do
f1
done
}
function f4 {
for i in $files
do
f2
done
}

as you can tell, f3 and f4 are just the loop, the only difference is the function...

I want to consolidate f3+4 to f5

function f5 {
function = $1
for i in $files
do
function
done
}

in my main program, I can then do

f5 f1
f5 f2

is that possible?
6 REPLIES 6
Sandman!
Honored Contributor
Solution

Re: pass function as an argument

You can pass the consolidated function some sort of a flag that dictates what the function should do after looking at its value; something like...

function f5 {
flag=$1
for i in $files
do
if [ $flag = "f1" ]; then

elif [ $flag = "f2"]; then

fi
done
}

f5 arg

hope it helps!
A. Clay Stephenson
Acclaimed Contributor

Re: pass function as an argument

Yes although your syntax isn't quite rigorous:
I'll do a simplifed version:

function f1 {
echo "Function f1"
return 1
} # f1

function f2 {
echo "Function f2"
return 2
} # f2

function f5 {
typeset -i ISTAT=0
func=${1}
shift
${func}
ISTAT=${?}
return ${ISTAT}
} # f5

f5 f1
f5 f2
If it ain't broke, I can fix that.
Gemini_2
Regular Advisor

Re: pass function as an argument

yes, that is my alternative. I guess that I just want to know how flexible shell is..
Gemini_2
Regular Advisor

Re: pass function as an argument

that is not straightforward...

but, thank you...I am glad that it can be done!
Gemini_2
Regular Advisor

Re: pass function as an argument

I still want to learn more...

typeset -i ISTAT=0
#define a variable ISTATE right?
func=${1}
#what does it mean?

shift
${func}
#func is now variable right?
ISTAT=${?}
return ${ISTAT}
} # f5
A. Clay Stephenson
Acclaimed Contributor

Re: pass function as an argument

More than anything, it means that I am a disciplined shell programmer. That's why you will always see my variables enclosed in {}'s.

typeset -i ISTAT=0 #declare ISTAT to be an integer (-i) variable and local to this function so that if there is another ISTAT elsewhere it does not interfere with this ISTAT

func=${1} #
and better still:
typeset func=${1}
#what does it mean?

It means that I taking the 1st parameter and turning it into a local variable eventgough it's the name of a function.

shift # clean up the parameter stack
${func}
#func is now variable right? Yes so that
${func} is now "f1" for example.
ISTAT=${?} # get the exit status of the last command and store it in ISTAT
return ${ISTAT} # returns a valid status to the calling routine
} # f5

Much of this (especially typeset) is documented in man sh-posix.
If it ain't broke, I can fix that.