LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   functions in bash scripting (https://www.linuxquestions.org/questions/programming-9/functions-in-bash-scripting-725582/)

wvw 05-12-2009 10:50 PM

functions in bash scripting
 
Hello

I would like to know if bash can only handle a function by itself or whether a fucntion can be used where it accepts a variable from the main program? From my reading on bash scripting sites it looks like the former is possible. below is an e.g. of what I mean:

#!/bin/bash
#
#Script to clarify my above question about functions used in bash
#test function
#
testintvalue(x)
{
if [$x == 5]; then
y=x+3 else
y=3
echo $y "is the total value"
fi
}
#
#Main program lines here
#
clear
echo "Welcome! Please type in a number between 1 and 9 inclusive"
read num
#Call the above function with the value of num passed to it
testintvalue(num)
#end of script

I know the above might have some syntax errors regarding the if statement etc, but what's important to me is if I can pass variables to the function like I did above.

Thanks
wvw

chrism01 05-13-2009 12:10 AM

Fns certainly can take params: http://www.tldp.org/LDP/abs/html/complexfunct.html

Alien_Hominid 05-13-2009 01:36 AM

When I was reading abs I found it rather buggy and plenty of text was not related to bash directly. Maybe is it me only being overly captious.

jlinkels 05-13-2009 09:39 AM

When writing a function in Bash you do NOT specify parameters in the function declaration. Inside the function you refer to parameters positionally, $1, $2 etc. These parameters are local to a function, hence not the command line parameters.

You pass parameters to a function by appending the call with parameters:
Code:

myfunc parm1 parm2
So if you have on the command line one parameter, and you want to pass that to you function:
Code:

myfunc $1
Run you program with sh -x youprogram while developing, it helps understand where the values go.

jlinkels

wvw 05-14-2009 05:22 PM

Hi Guys

Thanks for all the help :) That was exactly what I was looking for.

Cheers
wvw


All times are GMT -5. The time now is 01:27 AM.