How do i keep a variable local to the function in a bash shell script?
-
Variables inside functions are global, that means they keep the value set both inside and outside the function.
If you want to keep the variable local to the function you can use the local command.
as in the following example.
fruit_show() { local stall_number=10 echo "On the central display at the show today are $1 and $2" echo "The central display, is stall number $stall_number" } echo $stall_number fruit_show apples oranages
Running the script.
./functionparms.sh On the central display at the show today are apples and oranages The central display is stall number 10
Line number 2 sets the local variable in the function, trying to print the variable value outside of the variable, is blank, as seen in line number 7, nothing is printed.
© Lightnetics 2024