Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring global variable inside a function

Tags:

scope

bash

shell

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.

like image 212
Leonid99 Avatar asked Mar 26 '12 11:03

Leonid99


People also ask

How do you bring a global variable to a function?

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.

Can you declare a global variable in a function in C?

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.

How do you declare a global variable inside a function in Java?

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.

How do you assign a global variable to a function in Python?

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.


1 Answers

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.

like image 156
kipibenkipod Avatar answered Sep 19 '22 04:09

kipibenkipod