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.

I've written the following script to set some environment variables when needed.

#!/bin/sh
export BASE=/home/develop/trees
echo $BASE
export PATH=$PATH:$BASE
echo $PATH

Below the command and the results I can see on my terminal: the script runs, but the variables are not set at the end.

~$: ./script.sh
/home/develop/trees
/bin:......:/home/develop/trees
~$: echo $BASE

~$: 

What's wrong? Thanks in advance. Mirko

share|improve this question

3 Answers 3

up vote 34 down vote accepted

export exports the variable assignment to sub-shells, i.e. shells which are started as child processes of the shell containing the export directive. Your command-line environment is the parent of the script's shell, so it does not see the variable assignment.

You can use the source bash command to execute the script commands in the current shell environment and achieve what you want, e.g.

source script.sh
echo $BASE

Will produce

/home/develop/trees

The . command is a synonym for source which is often seen in scripts.

. script.sh     # identical to "source script.sh"
share|improve this answer
9  
You don't need export to pass variables on to subshells, a subshell is a copy of your current shell, including variables and functions etc. Exported variables gets copied to new processes spawned from the shell, regardless of that process being another shell or not. Secondly, . is the POSIX command for sourcing. Bash adds source as a more readable synonym for it, but you can't rely on it being available in sh. Lastly . ./script instead of . script if you want to avoid surprises. mywiki.wooledge.org/BashFAQ/060 –  geirha Jul 18 '11 at 5:55

When you run a script, it runs in a subshell. Variables are only valid within the context of that subshell. Set them in your .bashrc or .profile and read a basic bash programming manual. The export statement works down hierachy (current shell and all it's subshells) not up as in your example.

Alternatively (if you really want the script to effect the enviroment of your current shell) run it as:

. ./script.sh

That causes it to run in your current shell but will not pass variables up the hierarchy either.

share|improve this answer

I often want to set an environment variable without hassle.

Here is what I add to my .bashrc to implement this convenience.

defect() {
    if [ $1 ] && [ -z $2 ]
    then
        eval 'export DEFECT=$1'
        return 0
    else
        echo 'Usage: defect {number}'
        return 1
    fi
}
share|improve this answer

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.