Operating System - Linux
1819965 Members
3439 Online
109607 Solutions
New Discussion юеВ

Re: invoking a function with parameter

 
SOLVED
Go to solution
Maciej Szewczykowski
Frequent Advisor

invoking a function with parameter

hi all.
how to invoke a function so it takes certain values as parameters?
the point is: i've got a function that work with two variables (v1, v2). i'd like to make it work each time with different values of these variables. where should the function take values from (command line? file?)
how to make it work?
8 REPLIES 8
Mark Grant
Honored Contributor

Re: invoking a function with parameter

Lets assume you mean a shell script for the moment. When you call the function, just use your values as arguments and within the function reference them as $1 $2 etc etc.

Hope this helps.

Never preceed any demonstration with anything more predictive than "watch this"
Maciej Szewczykowski
Frequent Advisor

Re: invoking a function with parameter

Mark, could you please write a short example? (i mean how to send values to the function)
Mark Grant
Honored Contributor
Solution

Re: invoking a function with parameter

function myecho {
echo $1
}

myecho hello
exit

I don't know if you can prototype functions so its safer to just declare the functions first.
Never preceed any demonstration with anything more predictive than "watch this"
Jerome Henry
Honored Contributor

Re: invoking a function with parameter

Write :
v1=3
v2=7
echo $v1
3
echo $v2
7

hth

J
You can lean only on what resists you...
Maciej Szewczykowski
Frequent Advisor

Re: invoking a function with parameter

quick question - quick answer. thanks a lot guys.
Graham Cameron_1
Honored Contributor

Re: invoking a function with parameter

Didn't you ask this yesterday in the HP forums ??
http://forums1.itrc.hp.com/service/forums/questionanswer.do?threadId=233360
--
Anyway, within the function, just refer to $1, $2 as your parameters, and call it using syntax "yourfunc p1, p2".
Example: function leave takes an optional single parameter
--
function leave {
[ -n "$1" ] && exit_cd=$1
exit $exit_cd
}
-- and can be called in 2 ways --
leave 1
leave
--
--Graham
Computers make it easier to do a lot of things, but most of the things they make it easier to do don't need to be done.
Mark Grant
Honored Contributor

Re: invoking a function with parameter

And another, just to show some looping


function addten {
b=`expr $1 + 10`
echo "$1 plus 10 is $b"
}

for i in 10 23 4 65
do
addten $i
done
Never preceed any demonstration with anything more predictive than "watch this"
Maciej Szewczykowski
Frequent Advisor

Re: invoking a function with parameter

that's right. thank you once more.