I have a simple bash script:
#!/bin/bash
JAVA_HOME=/usr
EC2_HOME=~/ec2-api
echo $EC2_HOME
export PATH=$PATH:$EC2_HOME/bin
I run the script like so
$ ./ec2
/Users/user/ec2-api
The script runs and produces the correct output.
However, when I now try to access the EC2_HOME variable, I get nothing out:
$ echo $EC2_HOME
I get a blank string back. What am I doing wrong?
Do either of the following instead:
or
(note the
.notation is just a shortcut forsource)Explanation:
./ec2actually spawns a subshell from your current shell to execute the script, and subshells cannot affect the environment of the parent shell from which it spawned.EC2_HOMEdoes get set to/Users/user/ec2-apicorrectly in the subshell (and similarly thePATHenvironment variable is updated and exported correctly in the subshell as well), but those changes won’t propagate back to your parent shell.sourceruns the script directly in the current shell without spawning a subshell, so the changes made will persist.export: export is used to tell new shells spawned from the current shell to use the variables exported from the current shell. So for any variables you would only use in the current shell, they need not be exported.)