What I want to do is following. Inside a function, I need to assign a value to a variable, whose name is taken from another variable. In other words:
func() { # # Here happens something that ultimately makes $arg="var_name" # declare -g ${arg}=5 } func echo ${var_name}; # Prints out "5"
The code snippet above works great in bash 4.2. However, in bash before 4.2, declare
doesn't have the -g
option. Everything I found at google says that to define the global variable inside a function, I should just use the var=value
syntax, but unfortunately var
itself depends on another variable. ${arg}=5
doesn't work, either. (It says -bash: var_name=5: command not found
.
For the curious, the reason for all this is that this function actually creates global variables from the script parameters, i.e. running script --arg1=val
automatically creates variable named arg1
with value val
. Saves tons of a boilerplate code.
Using the “global” Keyword. To globalize a variable, use the global keyword within a function's definition. Now changes to the variable value will be preserved.
The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.
To define a Global variable in java, the keyword static is used. Java actually doesn't have the concept of Global variable, it is known as class variable ( static field ). These are the variables that can be used by the entire class. // constructer used to initialise a Student object.
Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.
declare
inside a function doesn't work as expected. I needed read-only global variables declared in a function. I tried this inside a function but it didn't work:
declare -r MY_VAR=1
But this didn't work. Using the readonly
command did:
func() { readonly MY_VAR=1 } func echo $MY_VAR MY_VAR=2
This will print 1 and give the error "MY_VAR: readonly variable" for the second assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With