# Understanding Environmental Variables in Linux
Environmental variables in Linux are key-value pairs stored in the system’s environment, used to pass information into processes launched from the shell. These dynamic values can significantly affect the behavior of running processes.
- Key-Value Structure: Variables are defined by a key (name) and value, like
PATH=/usr/bin:/bin
, wherePATH
is the key and/usr/bin:/bin
is the value. - Purpose and Usage: They store system settings and preferences such as executable file directories (
PATH
), user’s home directory (HOME
), and default editor (EDITOR
). - Scope and Accessibility: Can be system-wide (in
/etc/environment
) or user-specific (in.bashrc
or.bash_profile
). - Dynamic Configuration: Enables dynamic system configuration without changing executable binaries, useful in scripts and batch processes.
- Inheritance: Child processes inherit environmental variables from their parent, allowing settings to pass down.
# Viewing Environmental Variables
printenv
: Displays all environment variables. Example:printenv
.- For a specific variable:
echo $VARIABLE_NAME
. Example:echo $PATH
.
# Setting Environmental Variables
- Temporary Assignment: For the current session. Example:
export VARNAME=value
. - Permanent Assignment: Add to profile file and reload. Example: Add
export VARNAME=value
to.bashrc
and runsource .bashrc
.
# Modifying Environmental Variables
- Append or modify existing variables. Example:
export PATH=$PATH:/new/path
.
# Unsetting Environmental Variables
unset
: Removes a variable from the current session. Example:unset VARNAME
.
# Important Points
- Distinguish between environment and shell variables.
- Persistence requires writing to shell’s profile scripts like
.bashrc
. - System-Wide vs User-Specific: Set in
/etc/environment
or.bashrc
. - Common Variables:
PATH
,HOME
,USER
,PWD
,OLDPWD
.
# Example: Adding a Directory to the PATH
- View the current PATH:
echo $PATH
. - Append a new directory:
export PATH=$PATH:/usr/local/newdir
. - Verify the change:
echo $PATH
. - For permanence, add to
.bashrc
and reload withsource .bashrc
.
# Conclusion
Mastering environmental variables in Linux enhances system customization and control. They provide a flexible way to configure system settings and manage process communication, vital for both system administrators and users. Proper management of these variables is key to leveraging Linux’s full capabilities.