Working with Environment Variables on Linux
In Linux, environment variables are dynamic values that can affect the behavior of processes and programs. They are essentially key-value pairs that are accessible to all running processes. Here are some key points about Linux environment variables:
1. Setting Environment Variables:
- Temporary: You can set an environment variable for the current session in the terminal using the
export
command. For example:
export VARIABLE_NAME=value
- Permanent: To make an environment variable persistent across sessions, you can add it to the configuration files like
'.bashrc'
, ‘.bash_profile
‘, or ‘/etc/environment
‘ depending on your shell.
2. Viewing Environment Variables:
- To view all environment variables, you can use the ‘
printenv'
command or ‘env'
. - To view a specific environment variable, use
'echo $VARIABLE_NAME
‘.
3. Common Environment Variables:
PATH
: A list of directories where the system looks for executable files. Each directory is separated by colons (:) and it is in the format ‘PATH=/directory1:/directory2
‘.HOME
: This variable points to the current user’s home directory, typically/home/username
.USER
orLOGNAME
: These variables store the current username.PS1
: This variable sets the shell prompt.LANG
orLC_ALL
: These variables define the system’s default locale settings.
4. Modifying Environment Variables:
- To change the value of an environment variable in the current session, simply reassign it.
VARIABLE_NAME=new_value
- To permanently change an environment variable, you’ll need to edit one of the shell’s configuration files.
5. Special Environment Variables:
$$
: PID (Process ID) of the current shell.$?
: Exit status of the last command.$0
: The name of the current script or program.
6. Passing Environment Variables to Processes:
- You can pass environment variables to a process by defining them before the command. For example:
VARIABLE_NAME=value command
7. Creating Custom Environment Variables:
- You can create your own custom environment variables for specific applications or scripts. Simply set them as shown in point 1.
8. Removing Environment Variables:
- To remove an environment variable, you can use the
unset
command. For example:
unset VARIABLE_NAME
Remember that environment variables are case-sensitive and typically in uppercase. They play a crucial role in how your Linux system operates, and understanding how to manage them can be important for configuring your environment to suit your needs.