Setting and Exporting Environment Variables

Understanding Environment Variables in Shell

Environment variables are dynamic variables that store information used by the shell and applications. They are crucial for configuring the behavior of scripts and processes. Variables can be set locally within a script or globally, and their values can be accessed across different shells or processes. Understanding how to set and export these variables is essential for effective shell scripting.

Setting Environment Variables

Environment variables can be set in several contexts:

  • In a script: Use export to make the variable available to child processes.

    export MY_VAR="Hello, World!"  
    
  • In a file: Define variables in a .bashrc or .zshrc file and source it with source.

    echo "export MY_VAR='Hello, World!'" >> ~/.bashrc  
    source ~/.bashrc  
    
  • At the command line: Use set to define variables in the current shell.

    set MY_VAR="Hello, World!"  
    

    Note that set defines variables locally, while export makes them global.

Exporting Environment Variables

Exporting makes variables accessible to child processes, which is vital for scripts that need to inherit settings. Key points include:

  • Using export:

    export PATH=$PATH:/new/bin  
    

    This appends the new directory to the existing PATH variable.

  • Global vs. Local Variables:

    • export makes variables global.
    • set defines variables locally.
  • Unsetting Variables:

    unset MY_VAR  
    

    Removes the variable from the environment.

Practical Examples

  1. Setting a Variable in a Script:

    #!/bin/bash  
    export USER="john_doe"  
    echo "$USER"  
    

    This script sets USER to "john_doe" and outputs it.

  2. Exporting PATH for All Processes:

    export PATH="/usr/local/bin:$PATH"  
    

    This ensures that the script runs with the new path.

  3. Using Environment Variables in Commands:

    echo "$HOME"  
    

    Displays the user's home directory, which is resolved from the environment.

Common Pitfalls

  • Missing Quotes:

    MY_VAR=Hello world  
    

    Without quotes, Hello world becomes a single token.

  • Overriding Variables:

    export MY_VAR="New Value"  
    

    Overwrites the previous value.

Conclusion

Setting and exporting environment variables is fundamental to shell scripting. By mastering these concepts, users can create scripts that are flexible, maintainable, and efficient. Understanding the difference between local and global variables, and how to manage them through export and set, ensures that scripts inherit the correct settings and avoid unintended behavior.