Environment Variables and PATH
Category: Linux Command Basics
Type: Linux Commands
Generated on: 2025-07-10 03:07:38
For: System Administration, Development & Technical Interviews
Environment Variables and PATH Cheatsheet (Linux)
Section titled “Environment Variables and PATH Cheatsheet (Linux)”This cheatsheet covers environment variables and the PATH variable in Linux, providing practical examples and tips for sysadmins and developers.
1. Command Overview
Section titled “1. Command Overview”- Environment Variables: Store configuration information that can be accessed by processes. Used to customize application behavior, store sensitive information, and manage system settings.
- PATH: A special environment variable that tells the shell where to look for executable files (commands). When you type a command, the shell searches the directories listed in the PATH variable to find the corresponding executable.
2. Basic Syntax
Section titled “2. Basic Syntax”Environment Variables:
- Setting:
VARIABLE_NAME=value - Accessing:
$VARIABLE_NAMEor${VARIABLE_NAME}(safer for variable names with special characters) - Exporting:
export VARIABLE_NAME(makes the variable available to child processes) - Unsetting:
unset VARIABLE_NAME
PATH:
- Displaying:
echo $PATH - Adding to PATH (Temporary):
PATH=$PATH:/path/to/new/directory - Adding to PATH (Persistent): Edit shell configuration files (e.g.,
.bashrc,.zshrc)
3. Practical Examples
Section titled “3. Practical Examples”Environment Variables:
# Setting a simple environment variableMY_VARIABLE="Hello, World!"
# Accessing the variableecho $MY_VARIABLE# Output: Hello, World!
# Exporting the variableexport MY_VARIABLE
# Running a command that uses the variableecho "The value is: $MY_VARIABLE"# Output: The value is: Hello, World!
# Setting a variable with spaces (needs quotes)MY_VARIABLE="This is a string with spaces"echo $MY_VARIABLE# Output: This is a string with spaces
# Using environment variables in scriptscat > my_script.sh <<EOF#!/bin/bashecho "The script is running as user: $USER"EOFchmod +x my_script.sh./my_script.sh# Output: The script is running as user: your_username
# Unsetting a variableunset MY_VARIABLEecho $MY_VARIABLE# Output: (empty string)PATH:
# Displaying the current PATHecho $PATH# Adding a directory to the PATH temporarilyPATH=$PATH:/opt/my_program/binecho $PATH# Output: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin:/opt/my_program/bin
# Verify the command in the new path is now executable# Assuming /opt/my_program/bin contains an executable named 'my_command'my_command # Now should execute without specifying the full path
# Persistent PATH Modification (using .bashrc)# Edit ~/.bashrc and add the following line:# export PATH=$PATH:/opt/my_program/bin# Then, source the file:source ~/.bashrc
# Now the PATH change is permanent for new shell sessions4. Common Options
Section titled “4. Common Options”Environment Variables:
export: Makes a variable available to subsequently executed commands.unset: Removes a variable from the environment.env: Prints a list of all environment variables. Also used to run a command with a modified environment.printenv: Prints the value of a specific environment variable.
PATH:
- No specific options for PATH itself, but
whichandtypeare helpful for verifying command locations.
5. Advanced Usage
Section titled “5. Advanced Usage”Environment Variables:
# Using env to run a command with a temporary environment variableenv MY_TEMP_VAR="Temporary Value" bash -c 'echo $MY_TEMP_VAR'# Output: Temporary Valueecho $MY_TEMP_VAR # Outside the env command# Output: (empty string, as the variable was only set for the env command)
# Using environment variables for secure storage (e.g., API keys)# NOT RECOMMENDED FOR SENSITIVE DATA IN PRODUCTION. Use secure storage solutions (e.g., Vault)API_KEY="YOUR_API_KEY"export API_KEY
# Accessing the API key in a scriptcat > api_client.sh <<EOF#!/bin/bashcurl "https://api.example.com/data?key=$API_KEY"EOFchmod +x api_client.sh./api_client.sh
# Using default values if a variable is not setecho "${MY_VAR:-Default Value}" # If MY_VAR is not set, prints "Default Value"
# Using environment variables to configure Docker containers# (Example Dockerfile snippet)# ENV APP_PORT=8080# EXPOSE $APP_PORTPATH:
# Prepending a directory to the PATH (higher precedence)PATH=/opt/my_program/bin:$PATHecho $PATH
# Restoring the default PATH# (Often useful after accidentally modifying it)# This depends on the specific distribution. Often stored in /etc/environment or /etc/profile.d/*.sh# Example (Debian/Ubuntu):PATH=$(getconf PATH)echo $PATH
# Using 'which' to find the location of a commandwhich ls# Output: /usr/bin/ls
# Using 'type' to determine if a command is an alias, function, or executabletype ls# Output: ls is aliased to `ls --color=auto'type -a ls # Show all matching command types6. Tips & Tricks
Section titled “6. Tips & Tricks”- Use
.envfiles for development: Create a.envfile in your project directory to store environment variables used during development. Load the variables usingsource .env(or a tool likedotenv). Do not commit.envfiles to version control (add them to.gitignore). - Be careful when modifying the PATH: A broken PATH can make your system unusable. Always test changes in a non-critical environment first.
- Use
sudo envto preserve environment variables: When usingsudo, it usually cleans the environment.sudo envcan preserve some environment variables.sudo -Epreserves the user’s environment. - Use
declare -xfor exporting: Equivalent toexport VARIABLE_NAME. - Variable substitution can be nested:
echo "Value of variable is ${!VAR_NAME}"(where VAR_NAME is another variable holding the name of the desired variable).
7. Troubleshooting
Section titled “7. Troubleshooting”- Command not found: This usually means the executable is not in your PATH. Verify the path and ensure it’s correctly added to the PATH variable. Also, check the executable’s permissions (
chmod +x). - Environment variable not being recognized in a script: Make sure the variable is exported (
export VARIABLE_NAME) before running the script. Also, ensure the variable name is spelled correctly in both the setting and accessing locations. - PATH changes not persisting: Ensure you are modifying the correct shell configuration file (e.g.,
.bashrc,.zshrc,.profile) and that yousourcethe file or restart your shell session for the changes to take effect. - Accidentally overwriting the PATH with a single directory: This is a common mistake. Always append or prepend to the existing PATH using
$PATH. If you overwrite it, you’ll need to restore the default PATH (see “Advanced Usage”).
8. Related Commands
Section titled “8. Related Commands”env: Print or run a command in a modified environment.printenv: Print environment variables.export: Set environment variables.unset: Unset environment variables.which: Locate a command.type: Describe a command type (alias, function, executable).locate: Find files by name.find: Search for files in a directory hierarchy.getconf: Query configuration variables.sudo: Execute a command as another user.grep: Search for patterns in files.
This cheatsheet provides a comprehensive overview of environment variables and the PATH variable in Linux. Remember to always test changes in a safe environment before applying them to production systems. Remember to consult the man pages for the most up-to-date and detailed information (man env, man bash, etc.).