LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   How to change function parameter value and return back to the main shell program (https://www.linuxquestions.org/questions/linux-general-1/how-to-change-function-parameter-value-and-return-back-to-the-main-shell-program-138795/)

Bassam 01-26-2004 08:49 AM

How to change function parameter value and return back to the main shell program
 
Hi All,
In shell programming, I am trying to call a function and pass parametrs to it, I want to change the values of the parameters and return them back to the main shell script, so anyone could help me in this matter???

example:

Code:

#!/bin/bash
function names ()
{
        echo -e "Inside the function $1"
        echo -e "Inside the function $2"

        #here I am changing the values of the parameters.
        $1=Sahab
        $2=Alaa

        return
}

name1=Bassam
name2=Farah

echo -e "$name1\n"
echo -e "$name2\n"

names $name1 $name2

echo -e "$name1\n"
echo -e "$name2\n"

that was the first part of my question. Now the second part is that is it possible to return a value with the return keyword from inside the function to the main program?

example
Code:

#!/bin/bash
function addition ()
{
        return `expr $1 + $2`
}

echo < addition 5 10

Please correct if I am mistaken


Regards
Bassam

jim mcnamara 01-26-2004 10:02 AM

You have to use variables that retain scope in and out of the function
Code:

#!/bin/bash
name1=""
name2=""
function names ()
{
        echo -e "Inside the function $1"
        echo -e "Inside the function $2"

        #here I am changing the values of the parameters.
        # $1 and $2 -- these are local ONLY to the function

        name1=$1
        name2=$2
       
        return
}

name1=Bassam
name2=Farah

echo -e "$name1\n"
echo -e "$name2\n"

names "XXX" "ZZZZ"

echo -e "$name1\n"
echo -e "$name2\n"



All times are GMT -5. The time now is 06:04 AM.