I've defined an Env variable :
export NBR_PROCESS=2
basically I should be able to update the variable, but when I execute the following script I get the same result on each run:
#!/bin/bash
echo "Script 2: Before decrement : $NBR_PROCESS"
export NBR_PROCESS=$(($NBR_PROCESS - 1))
echo "Script 2: After decrement : $NBR_PROCESS"
on each execution I get the same following result:
Script 2: Before decrement : 2
Script 2: After decrement : 1
What I would like to do is decrement the variable NBR_PROCESS by running the script.
Any idea what I've missed here ? Thank you !
You have to "source"
source
your_script
EDIT 1
See this answer...
EDIT 2
. filename [arguments]
orsource filename [arguments]
Complete explanations:
Each time you run your script, it gets a fresh copy of your (or the user it's being executed as) environmental variables - and they stay local to that process. In other words, whatever variables are modified are only modified for that instance.
If the process creates child processes, same thing. The children receive a copy of the parent's environment and any changes they make will "disappear" when they exit.
As Luc M stated, you can use
source
to have your script(s) execute as Tlc processes. This will allow the contents of said script to also affect your environment.A script (or any executable) cannot change an environment variable of the shell, because it is running in a different (child) process. The only way to change the environment inside your shell is thru the
export
builtin. You could also use theenv
command to setup the environment of some program, likeenv YOURVAR=1 yourprogram yourarguments
...You could use bash functions or the
eval
orsource
builtins (to indirectly invoke theexport
builtin).Read the advanced bash scripting guide