1833870 Members
1763 Online
110063 Solutions
New Discussion

Function call in script

 
SOLVED
Go to solution
Sanjay Tailor
Frequent Advisor

Function call in script

Hello all,

I am writing a script that requires the user to input 3 variables. To make the program more robust, I want to check each variable just to see if anything has been entered. If nothing has been entered the user is prompted to enter again.

Instead of writing the same script piece 3 times, my thinking was to write a function that would check to see if anything had been entered.

My problem is: How can I call the function 3 times with 3 different variables and have it return the correct variables? I have attached the program as it stands and so far I have it checking the 1st variable. I want to use the same function to check all 3 variables.

Thank you.
Sanjay

3 REPLIES 3
Darrell Allen
Honored Contributor
Solution

Re: Function call in script

Hi Sanjay,

I'm not a script guru but you could do something like this:

#!/bin/sh
#
function checknum
{
echo "Enter "$PROMPT": \c"
read VAR
while [ "$VAR" = "" ]
do
echo "You must enter "$PROMPT" (Ctrl-C to quit)\n"
echo "Enter "$PROMPT": \c"
read VAR
done
}
#
PROMPT="Input base"
checknum
ib=$VAR
#
PROMPT="Output base"
checknum
ob=$VAR
#
PROMPT="Number to convert"
checknum
newin=$VAR
#
echo Input base: $ib
echo Output base: $ob
echo Number to convert: $newin

Darrell
"What, Me Worry?" - Alfred E. Neuman (Mad Magazine)
Sanjay Tailor
Frequent Advisor

Re: Function call in script

Hello Darrell,

Thank you for that. Your suggestion worked just fine.

Thanks again,
Sanjay
Bill Hassell
Honored Contributor

Re: Function call in script

You can call a function with values. They work just like running a script:

#!/usr/bin/sh
function TestParams
{
echo "$# params, 1=$1, 2=$2, all=$@"
return
}

TestParams 1 2 3 4 5
TestParams 123 456

---

Now to pass a parameter and modify the value, the easiest is to export the parameter at the start of the script. Now, all functions will know about this parameter and it won't have to be passed to the function in the call.


Bill Hassell, sysadmin