2

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?

2 Answers 2

5

Do either of the following instead:

source ec2

or

. ec2

(note the . notation is just a shortcut for source)

Explanation:

  • This is because ./ec2 actually 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.
  • Thus, EC2_HOME does get set to /Users/user/ec2-api correctly in the subshell (and similarly the PATH environment variable is updated and exported correctly in the subshell as well), but those changes won't propagate back to your parent shell.
  • Using source runs the script directly in the current shell without spawning a subshell, so the changes made will persist.
  • (A note on 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.)
Sign up to request clarification or add additional context in comments.

Comments

0

A shell script can never modify the environment of their parent. To fix your problem, you can use the dot (.) command:

$ . ./ec2

and that should work. In cshell, it would be

% source ./ec2

To learn more about shells and scripts, my best resource is by far Unix power tools.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.