title: How to modify a global variable within a function in bash?
body: <p>I'm working with this:</p>
  
  <pre><code>GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
  </code></pre>
  
  <p>I have a script like below:</p>
  
  <pre><code>#!/bin/bash
  
  e=2
  
  function test1() {
    e=4
    echo "hello"
  }
  
  test1 
  echo "$e"
  </code></pre>
  
  <p>Which returns:</p>
  
  <pre><code>hello
  4
  </code></pre>
  
  <p>But if I assign the result of the function to a variable, the global variable <code>e</code> is not modified:</p>
  
  <pre><code>#!/bin/bash
  
  e=2
  
  function test1() {
    e=4
    echo "hello"
  }
  
  ret=$(test1)
  
  echo "$ret"
  echo "$e"
  </code></pre>
  
  <p>Returns:</p>
  
  <pre><code>hello
  2
  </code></pre>
  
  <p>I've heard of <a href="https://superuser.com/a/628865/235245">the use of eval</a> in this case, so I did this in <code>test1</code>:</p>
  
  <pre><code>eval 'e=4'
  </code></pre>
  
  <p>But the same result.</p>
  
  <p>Could you explain me why it is not modified? How could I save the echo of the <code>test1</code> function in <code>ret</code> and modify the global variable too?</p>