Davis Smith
Davis Smith

Reputation: 11

How can I get an environmental variable to persist in Bash?

I am just starting to learn how to program (starting off with Python). I am on a Windows computer, but I have installed Bash and Ubuntu, because that is what my programming book told me to do.

With that being said, I am trying to simply get an environmental variable I created in File Explorer to show in Bash. I went to my profile via the C: disk and then users and then created a file called ".profile" which was a text document. In the text document, the first line was export x=100.

When I close and reopen Bash and then type "echo $x," nothing shows up. The next line is blank whereas I am trying to make it show 100. What is the reason?

Upvotes: 1

Views: 1918

Answers (2)

mabe02
mabe02

Reputation: 2734

In Bash, you can export any environment variable with the following syntax:

export FOO=bar

In order to make these environment variables available in your shell or in any other script, you need to source the file where you stored your variables:

source my_file
echo $FOO

You may refer to this article for additional examples: Bash source command

Usually, the shell programs allow you to source a profile file. For Ubuntu, you can refer to this Ask Ubuntu question to learn more on how to setup your shell: Why isn't .profile sourced when opening a terminal?

Upvotes: 0

Shaqil Ismail
Shaqil Ismail

Reputation: 1951

In your home directory the ~/.bashrc file for the user you are logged in as, you can add a variable on a new line in this file and save. The next time this file is loaded as this user, the variable should be accessible.

Upvotes: 2

Related Questions