BASH script to set environment variables not working

export exports the variable assignment to child processes of the shell in which the export command was ran. Your command-line environment is the parent of the script's shell, so it does not see the variable assignment.

You can use the . (or 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 source command, often seen in scripts, is a bash synonym for ., which is part of the POSIX standard (so . is available in dash, for example, but source isn't).

. ./script.sh     # identical to "source ./script.sh"

(. script.sh and source script.sh will first look for script.sh in PATH, so it's safer to specify the path to script.sh.)


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 up on variables and subshells. 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.


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
}