Global variables in bash
Dear LQ,
What is the "standard" way of programming in bash ? can my functions simply change global variables inside their code and the rest of my script expects global variables to be changed anytime, or do you write functions that take parameters and return values ? It is easy to receive or return a number or a string, but I still have to figure out how to receive/return multiple values. |
in bash you cannot return multiple values, or at least not recommended.
Better to use global variables. you might want to start here: https://www.thegeekstuff.com/2010/05/bash-variables/ (or a similar page) |
Code:
#!/usr/bin/bash Code:
bash ./test2.sh |
basically all variables in BASH are global except variables declared as 'local' in functions, and also parameters passed to functions ( $1 .. $n ).
|
Quote:
Quote:
Cheers... |
Quote:
|
^ I believe variables in functions are by default local unless they have been defined in the main script, and are unset once the function returns.wrong!
I once read a genius bit of advice, is to set a global RETVAL variable to avoid running functions in subshells, so instead of Code:
do_func() { echo bla; } Code:
RETVAL="" |
@ondoho yes, some bash builtins like read and select put their output in $REPLY.
|
Quote:
|
@pan64 good point, which makes the function responsible to unset it or to set
it to some conventional NULL value that the caller must check before proceeding. |
Quote:
And yes, you can unset that variable too. |
So that would be checking $? everytime you call a function ? (if you
want to get defensive). |
yes, that is the way - if you want to be on the safe side. But also you need to implement error handling in your functions, otherwise it is just pointless.
|
I would like to clarify that ALL variables not declared as local (in a function) are global to script and ONLY variables declared with local will stay that way inside the function.
Quick example: Code:
#!/usr/bin/env bash The above being the case, my default is to create sparing global variables and all others are local to their respective functions, even to the extent of having a main() function which is ultimately one of the only things actually called by the script: Code:
shebang |
Quote:
I just wanted to throw it in there; avoiding subshells is a bit of a pet peeve of mine. CPUs are so powerful nowadays people forget how to code as efficiently as possible. |
All times are GMT -5. The time now is 04:16 AM. |