franki3xe franki3xe - 3 months ago 14
Bash Question

How to source file from bash script

I'm trying to source a file with an environment variable from my bash script, but it doesn't work.

This is the content of my script (

test.sh
), which is located in
~/scripts/test.sh
.

#!/bin/bash
FILE_NAME=/tmp/source_file
touch $FILE_NAME
echo "export TEST=\"test\"" > $FILE_NAME
source $FILE_NAME


Then I use
alias
in
my ~/.bashrc
.

alias testScript=~/scripts/test.sh


But when I use my script
testScript
, it didn't set the environment variable.

Answer

Environment variables only flow downstream in the process tree.

When you type testScript to a bash process, it creates a child process and execs /bin/bash or whatever is set by #!

Any environment variables set there remain only with the child process. Export causes the variables to be copied to additional grandchildren (children of that child) that might be spawned from that child.

Nothing can copy back to a parent. You need to use source instead of running the file. See Jonathan's answer.

You could try editing the files ~/.bashrc or ~/.login to set enviornment variables you need frequently.

See also http://superuser.com/q/153371 and http://superuser.com/questions/18988/difference-between-a-b-and-export-a-b-in-bash for more explanation of export in bash.