Skip to main content

Using Zsh

Setting Environment Variables in zsh

Learn to set environment variables in Zsh, be it temporary or permanent.

The environment variable can be incredibly useful when working with scripts as you don't have to specify the value itself and use the environment variable instead.

But when you change to a different shell such as zsh, tasks like setting an environment variable may seem a tedious task.

So in this guide, I will walk you through two ways you can set environment variables in zsh:

  • A temporary method (using export command)
  • A permanent method (requires modifying config file)

Let's start with the first one.

Set environment variable in zsh temporarily

📋
Temporary variables will only be effective for the current session so if you logout or reboot, variables will be wiped out of your system.

Using the good old export command is the easiest way you can set the environment variable in zsh.

To create an environment variable using the export command, you'd have to follow the given command syntax:

export VARIABLE_NAME=VARIABLE_VALUE

For example, here, I created a variable named SAGAR storing a numeric value "786":

export SAGAR=786

As you can see, I have used the echo command to print the value of the variable but you can also use the printenv command as shown here:

echo $VARIABLE_NAME
OR
printenv $VARIABLE_NAME

But if the value you want to assign contains spaces, then you have to assign a value between quotation ("") marks as shown here:

export $VARIABLE_NAME="Value of variable"

If you don't use the quotation marks around the value of the variable, then it will consider the first part of the value separated by space:

Set environment variables in zsh permanently

To create a permanent environment variable in zsh, you'd have to make changes in the zsh config file.

First, open the zshrc file using the following command:

nano ~/.zshrc

Go to the end of the file in Nano to write new lines using Alt + / and create new environment variables using the following syntax:

export VARIABLE_NAME=VARIABLE_VALUE

For example, here I created an environment variable named MY_SYSTEM storing the name of my current Linux distro:

export MY_SYSTEM=Pop!_OS

Once done, save changes, exit from the editor, and source the zshrc file to take effect from the recently made changes:

source ~/.zshrc

Here's how to create alias in zsh

While creating environment variables was fun, the real productivity starts with creating an alias as you can create a two-character alias for a two-line command!

So if you want to skyrocket your productivity, then here's how to create an alias in zsh:

Configure and Use Aliases in Zsh
Turbo charge your Zsh experience by using aliases for commonly used command combinations.

I hope you will find this guide helpful.

Sagar Sharma