Technology Encyclopedia Home >How to set environment variables on Ubuntu?

How to set environment variables on Ubuntu?

To set environment variables on Ubuntu, you can use several methods depending on whether you want the variable to persist across sessions or just for the current session.

For the Current Session

You can set an environment variable for the current terminal session using the export command. For example:

export MY_VARIABLE="Hello World"

After running this command, MY_VARIABLE will be available in the current terminal session and any child processes it spawns.

For Persistent Settings

If you want the environment variable to persist across sessions, you need to add the export command to your shell's configuration file. Common configuration files include:

  • ~/.profile
  • ~/.bashrc (for Bash shell)
  • ~/.zshrc (for Zsh shell)

For example, to add a persistent environment variable using Bash, you would edit ~/.bashrc:

nano ~/.bashrc

Add the following line at the end of the file:

export MY_VARIABLE="Hello World"

Save and close the file, then apply the changes by sourcing the file or restarting the terminal:

source ~/.bashrc

Using Environment Files

Another method for setting environment variables, especially useful in deployment scenarios, is to use environment files. You can create a file, for example, env_variables, and list your variables there:

MY_VARIABLE="Hello World"
ANOTHER_VARIABLE="Another Value"

Then, source this file in your shell:

source env_variables

In Cloud Environments

When working in cloud environments, such as those provided by Tencent Cloud, you might set environment variables through the console or configuration files within your cloud services. For instance, when deploying applications on Tencent Cloud's Container Service for Kubernetes (TKE), you can define environment variables in the pod specification YAML file:

apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  containers:
  - name: my-container
    image: my-image
    env:
    - name: MY_VARIABLE
      value: "Hello World"

This approach ensures that your application runs with the necessary environment variables configured.