Learn how to setup and use environment variables in your command line.
Using Environment Variables on the command line is a great way to store data for use with commands or to make your bash scripts more dynamic. There are three main ways that you can create a variable on the command line:
- Creating a variable for the current shell only
- Creating a variable which is accessible only for the current session
- Creating a variable which persists over all shell sessions
Creating a variable for the current shell only
In order to create a variable you can simply write:
The variable name being on the left and it’s value on the right. *Note: *there cannot be any space between the *= *assignment operator on either side! This is create if you just want to assign a quick variable and then utitlise it on the current shell session you are using. For example you can then type:
echo $myvariable #Prints out 123
This unfortunately doesn’t make the variable available to other terminal / command prompt sessions that are running or to other scripts that may be running, even in your current shell. For that, you’ll need to *export *a variable.
Creating a variable for the current session
If you want to make a variable which is available to other scripts running in your shell session you will need to use the *export *keyword before defining your variable.
In the video tutorial, you’ll see that this makes the variable now available for access inside any scripts that run inside the current shell session. If you want to make a global, persistent variable that doesn’t disappear when a new session is started you will need to add it to your *.bashrc *file.
Creating a variable which persists
In order to create these variables that don’t disappear you simply add the exported variables, as in the step above, to a special file in your home folder. If you open your *.bashrc *file in your home folder you can add the exported variable.
It can be handy to add global environment variables to remember information about your local configuration but also provides a way of securing data on remote servers, especially when you consider the scoping of variables as outlined above. Got a question about environment variables? Just ask in the comments below :)