Ubuntu – BASH script to set environment variables not working


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

export BASE=/home/develop/trees
echo $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
~$: echo $BASE


What's wrong?
Thanks in advance.

Best Answer

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


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.)

Related Question