Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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:~$ 
share|improve this question
add comment

4 Answers 4

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

share|improve this answer
add comment

source yourfile.sh

This should do the needful.

share|improve this answer
add comment

Another possibility is to create a function in your .bashrc, and call that function within the current shell; this will save a little typing. You can still pass variables.

This is the method I use instead of an alias if I need a little more flexibility.

share|improve this answer
add comment

New process get copy of each exported variable.

You need to do one of:

  • do all operation on the same process (by sourcing the script in current shell)
  • keep value in common place (sqlite, flat file) and read/write it from each process
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.