Ubuntu – Why doesn’t changing a variable in a script alter it outside the script

bashcommand lineenvironment-variables

Let's say I export a variable with the terminal. After that I call a script that alters that variable to something else. But when I return to the terminal and echo the variable, it remains as its original value.

What can I do if I want like the variable to be changed and visible outside the script, not only there in the script. Here's an example of what I want to say:

ares@ares-HP-ProBook-4530s:~$ export package=tree
ares@ares-HP-ProBook-4530s:~$ cat script3.sh 

#! /bin/bash
#set -x
echo $package
apt-cache show $1 | head -1
if [ $? -eq 0 ]; then
    package=1
else
    package=0
fi
echo $package

Output when running script

ares@ares-HP-ProBook-4530s:~$ ./script3.sh gnome-terminal
tree
Package: gnome-terminal
1
ares@ares-HP-ProBook-4530s:~$ echo $package
tree
ares@ares-HP-ProBook-4530s:~$ 

Best Answer

Your shell process has a copy of the parent's environment and no access the parent process's environment whatsoever. When your shell process terminates any changes you've made to its environment are lost. Sourcing a script file is the most commonly used method for configuring a shell environment, you may just want to bite the bullet and maintain one for each of the two flavors of shell.

Found this answer here