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
Best Answer
export
exports the variable assignment to child processes of the shell in which theexport
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
.
(orsource
) bash command to execute the script commands in the current shell environment and achieve what you want, e.g.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, butsource
isn't).(
. script.sh
andsource script.sh
will first look forscript.sh
inPATH
, so it's safer to specify the path toscript.sh
.)