title: Declaring global variable inside a function
body: <p>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:</p>
  
  <pre><code>func() {  
    #  
    # Here happens something that ultimately makes $arg="var_name"
    # 
    declare -g ${arg}=5
  }
  
  func
  
  echo ${var_name}; # Prints out "5"
  </code></pre>
  
  <p>The code snippet above works great in bash 4.2. However, in bash before 4.2, <code>declare</code> doesn't have the <code>-g</code> option. Everything I found at google says that to define the global variable inside a function, I should just use the <code>var=value</code> syntax, but unfortunately <code>var</code> itself depends on another variable. <code>${arg}=5</code> doesn't work, either. (It says <code>-bash: var_name=5: command not found</code>.</p>
  
  <p>For the curious, the reason for all this is that this function actually creates global variables from the script parameters, i.e. running <code>script --arg1=val</code> automatically creates variable named <code>arg1</code> with value <code>val</code>. Saves tons of a boilerplate code.</p>