Your script can not change the environment of the calling process (shell), it merely inherits it.
So, if you export foo=bar
, and then invoke sh
(a new process) with your script, the script will see the value of $foo
(which is "bar"
), and it will be able to change its own copy of it – but that is not going to affect the environment of the parent process (where you exported the variable).
You can simply source
your script in the original shell, i.e. run
source increment_script.sh
or
. increment_script.sh
and that will then change the value of the variable.
This is because source
ing a script avoids spawning a new shell (process).
Another trick is to have your script output the changed environment, and then eval that output, for example:
counter=$[counter+1]
echo "counter=$counter"
and then run that as
eval `increment_script.sh`