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
exportto make the variable available to child processes.export MY_VAR="Hello, World!"In a file: Define variables in a
.bashrcor.zshrcfile and source it withsource.echo "export MY_VAR='Hello, World!'" >> ~/.bashrc source ~/.bashrcAt the command line: Use
setto define variables in the current shell.set MY_VAR="Hello, World!"Note that
setdefines variables locally, whileexportmakes 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/binThis appends the new directory to the existing
PATHvariable.Global vs. Local Variables:
exportmakes variables global.setdefines variables locally.
Unsetting Variables:
unset MY_VARRemoves the variable from the environment.
Practical Examples
Setting a Variable in a Script:
#!/bin/bash export USER="john_doe" echo "$USER"This script sets
USERto "john_doe" and outputs it.Exporting PATH for All Processes:
export PATH="/usr/local/bin:$PATH"This ensures that the script runs with the new path.
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 worldWithout quotes,
Hello worldbecomes 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.