Environment variables are a critical aspect of Linux systems. They define the working environment for processes, applications, and users by storing information such as file paths, system configurations, and session data. This chapter covers the tools and techniques for viewing, modifying, and managing environment variables effectively.
- Environment Variable: A key-value pair that influences the behavior of the system and applications.
- Types of Environment Variables:
- System-wide: Defined for all users, typically in
/etc/environment
or/etc/profile
. - User-specific: Defined for a specific user, stored in shell configuration files like
~/.bashrc
or~/.bash_profile
.
- System-wide: Defined for all users, typically in
$PATH
: Directories where the shell searches for executables.$HOME
: The user’s home directory.$SHELL
: The default shell for the user.$USER
: The username of the current user.
- Displays all environment variables or a specific one.
printenv # Show all variables
printenv PATH # Show the value of PATH
- Similar to
printenv
, lists all environment variables.
env
- Prints the value of a specific environment variable.
echo $HOME
- The variable exists only for the current session.
export VARIABLE_NAME=value
- Set a new variable:
export MY_VAR="Hello World"
- Verify the variable:
echo $MY_VAR
### Permanently Set a Variable
- Add the variable to a shell configuration file.
#### Example (for Bash):
1. Open `~/.bashrc` or `~/.bash_profile`:
```bash
nano ~/.bashrc
- Add the variable:
export MY_VAR="Persistent Value"
- Apply the changes:
source ~/.bashrc
The $PATH
variable determines where the shell looks for executables.
export PATH=$PATH:/new/directory
- Add
/usr/local/bin
to$PATH
:export PATH=$PATH:/usr/local/bin
- Make the change permanent:
Add the above line to
~/.bashrc
or~/.bash_profile
.
- Deletes a variable from the environment.
unset VARIABLE_NAME
unset MY_VAR
- Runs a command with a minimal environment.
env -i bash --noprofile --norc
- Lists all shell and environment variables.
set
/etc/environment
: Contains global environment variables./etc/profile
: Executes for all users at login.
~/.bashrc
: Executes for non-login Bash shells.~/.bash_profile
: Executes for login Bash shells.
By the end of this chapter, you should be able to:
- View environment variables using
printenv
,env
, andecho
. - Set and modify environment variables both temporarily and permanently.
- Customize and debug the
$PATH
variable. - Use configuration files to manage environment variables effectively.
- Move to Chapter 8: Bash Scripting to learn how to automate tasks using Bash scripts.
- Display all environment variables on your system using
env
. - Set a temporary environment variable and verify its value.
- Add a new directory to your
$PATH
and make it permanent. - Remove an environment variable using
unset
. - Identify the difference between
~/.bashrc
and/etc/environment
in your system.