Reputation: 3072
I'm writing a compiler that compiles into bash. It seems like a pain to declare some variables as local and some as global - I can declare variables as local even when I'm not inside a function. Is it a good idea to make all variables local in bash?
Upvotes: 1
Views: 1865
Reputation:
You should use global
variables only when needed because it makes it harder to debug; the bash official docs say this regarding local
variables:
local [option] [name[=value] ...] .
For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by declare. When local is used within a function, it causes the variable name to have a visible scope restricted to that function and its children. With no operands, local writes a list of local variables to the standard output. It is an error to use local when not within a function. The return status is 0 unless local is used outside a function, an invalid name is supplied, or name is a read‐ only variable.
You should local
variables only when you're in a function otherwise it will error.
You should also take a look at what variable scope means. If you make all variables global scope, then its going to be painful to debug. If you make var a
global scope, and then shadow it (accidentally maybe) within a function as var a
, creating a local scope, you'll make it even harder to debug.
Upvotes: 3