Can global variables be modified in bash function?

Global variables can be accessed in bash function without declaring anything and when these are modified the behaviour depend on whether function is called in sub-shell mode or inline mode. Sub-shell mode can be called with $(func_name) and inline can be just called with func_name. In sub-shell mode variables modified inside don’t impact variables outside with same name.

#!/bin/bash
f1 () {
  echo "in f1 x=$x"
  x=2
}

x=1
f1
echo "after call x=$x"

x=1
ret=$(f1)
echo "ret=$ret"
echo "after call x=$x"
in f1 x=1
after call x=2
ret=in f1 x=1
after call x=1
Env: GNU bash, version 4.3.11

Note that in sub-shell mode, echo output is not printed on stdout.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments