Reputation: 755
in my bash script i try to pass from the function ( function_2 ) a variable to the function ( function_1 ) unfortunately i didn't find how to do it properly :(
I search on internet but all the time i fall on different language ( ruby, python etc .. ) i try to do the same without success :(
function_1(){
echo "The value of : $VAR in function_2"
}
function_2(){
echo "the value of var if function_1 is : $VAR "
function_1
}
while getopts s: opt; do
case $opt in
s) VAR=$OPTARG
function_2
;;
esac
done
Upvotes: 1
Views: 120
Reputation: 17721
Arguments passed to functions as parameters in bash are accessible with $1
, $2
...
function_1() {
echo "The value of passed parameter in function_2 is: $1"
}
function_2() {
echo "the value of var in function_1 is: $VAR"
function_1 $VAR
}
while getopts s: opt; do
case $opt in
s) VAR=$OPTARG
function_2
;;
esac
done
Upvotes: 0
Reputation: 3826
You can pass on the variable as argument to the function when you call the function_1 for example:
function_1(){
VAR=$1
echo "The value of : $VAR in function_2"
}
function_2(){
echo "the value of var if function_1 is : $VAR "
function_1 $VAR
}
while getopts s: opt; do
case $opt in
s) VAR=$OPTARG
function_2
;;
esac
done
notice that you can directly access the passed on variable as $1 in function_1 without assigning it to VAR
Upvotes: 2