Environment variables are a critical component of Linux and Bash scripting. They store essential configuration settings, paths, and other system parameters. Often, Bash scripts need to check whether an environment variable exists and get its value if it does. This guide will provide an in-depth look at the various methods to check if an environment variable exists and retrieve its value in Bash.
What are Environment Variables?
Environment variables are dynamic named values managed by the operating system and available to running processes. Some common examples include:
- $PATH – Directories to search for executable programs
- $HOME – Home directory of the current user
- $LANG – System language settings
Environment variables control many aspects of the shell session and application behavior. Some key uses:
- Store system configuration options
- Set file system paths for executables
- Pass parameters between programs
- Customize shell behavior
When a process starts, it inherits a copy of its parent‘s environment variables. Changing an environment variable only affects the current shell session unless exported.
Understanding environment variables in Bash is vital for writing robust, portable shell scripts. Checking if a variable exists allows script logic to adapt to different systems. Retrieving the variable value lets scripts leverage configuration settings.
Why Check If Variables Are Set
Checking if an environment variable is set before attempting to use it is crucial for writing robust bash scripts that don‘t produce errors. Uninitialized variables evaluate to null strings which can cause scripts to exit prematurely. Testing if variables like API keys or file paths are set prevents unintended consequences.
Check If Environment Variable Exists in Bash
Here are some common techniques to test if an environment variable is defined in Bash:
1. Parameter Expansion with Default Value
Parameter expansion ${VAR:-default} expands to $VAR if set, otherwise expands to "default". The :- operator checks if $VAR is set:
if [ -n "${VAR:-}" ]; then
echo "VAR is set"
else
echo "VAR is not set"
fi
The -n Bash built-in checks if a string is not empty. If $VAR exists, ${VAR:-} expands to its value. If $VAR doesn‘t exist, ${VAR:-} expands to null.
2. Check Exit Status of echo $VAR
The echo command returns exit code 0 if its first argument expands to a non-empty string:
if echo "$VAR" | grep -q .; then
echo "VAR is set"
else
echo "VAR is not set"
fi
The output of echo $VAR is piped to grep. If $VAR expands to a non-empty value, grep matches due to its . argument. If $VAR is empty or unset, grep finds no matches.
3. Compare Parameter Expansion Lengths
Parameter expansion ${#VAR} returns the length of $VAR. Test if length > 0 to check if set:
if [ ${#VAR} -gt 0 ]; then
echo "VAR is set"
else
echo "VAR is not set"
fi
This compares the length ${#VAR} against 0 using the -gt numeric comparison operator. The test returns true if $VAR is set to any non-empty value.
Retrieve Value of Environment Variable
Once you‘ve checked an environment variable exists, retrieve its value in Bash scripts using:
1. Parameter Expansion ${VAR}
if [ -n "${VAR:-}" ]; then
echo "VAR is: ${VAR}"
fi
The ${VAR} syntax expands to the value of $VAR if set, otherwise expands to null. This is the standard method to reference an environment variable value in Bash.
2. Command Substitution $(printenv VAR)
if [ -n "${VAR:-}" ]; then
echo "VAR value: $(printenv VAR)"
fi
printenv displays environment variable values. Wrapping printenv VAR in $() performs command substitution, expanding the output in place.
3. Source File With export VAR=value
For reusable logic, define variables in scripts using export:
# vars.sh
export VAR=value
# script.sh
if [ -n "${VAR:-}" ]; then
. ./vars.sh
echo "VAR is $VAR"
fi
Sourcing vars.sh with . makes $VAR available to script.sh. export exposes $VAR to any child processes.
Setting Default Variable Values
When checking if variables are defined, optionally supply a default value like:
PORT=${PORT:-8080}
This guarantees $PORT will have a value if not already set.
Choose reasonable defaults that allow the script to run without failure. Log or print warnings when defaults get applied to increase visibility.
Practical Examples
Some use cases for checking if environment variables exist:
Detect Available Features
Applications often use environment variables as feature flags:
if [ -n "${FEATURE_X:-}" ]; then
# Run NEW_FEATURE code
else
# OLD FEATURE code
fi
Testing if $FEATURE_X exists allows optionally enabling new features, while maintaining backwards compatibility by default.
Store API Credentials Securely
Sensitive values like API keys shouldn‘t be hardcoded. Instead, export them as variables:
if [ -n "${API_KEY:-}" ]; then
call_api_with_key $API_KEY
fi
This safely passes $API_KEY to requests only if properly set.
Centralize Database Configuration
To manage database credentials cleanly:
DB_HOST="${DB_HOST:-localhost}"
DB_USER="${DB_USER:-test_user}"
# Connect to database
database_connect $DB_HOST $DB_USER
Default values for host and user enable connecting to a test database. But the production database is easily configured by setting $DB_HOST and $DB_USER explicitly.
Additional Examples
Other common cases:
- Toggling features – $NEW_UI to switch to new user interface flow
- Build versioning – increment $BUILD_NUM for each release
- Debug mode – $DEBUG to enable additional logs
Environment Variable Naming Conventions
Follow these standard naming practices for environment variables in Bash:
Syntax | Only alphanumeric chars and underscores, case-sensitive |
Style | Fully capitalized names by convention |
Namespaces | Prefix custom vars to avoid collisions |
As an example, custom application variables could follow the format:
APP_API_KEY=abcd1234
APP_DB_PASS=password
Securing Sensitive Variables
Take the following precautions when dealing with sensitive environment variables:
- Avoid leaking secret keys, passwords, API tokens into logs
- Set permissions to restrict access – 600 for files, 700 for scripts exporting sensitive variables
- Only export variables when essential for additional security
Env vars can also be misused for exploits if not properly handled:
- Never directly insert user input into variables
- Sanitize all user data before concatenating into variable values
Listing Available Environment Variables
There are a few handy commands to show all currently defined environment variables and their values:
printenv | Print all environment variables |
set | grep ^[A-Z] | Filter for exported vars |
env | Print all env vars |
The /proc/self/environ virtual file also contains the complete env variable list.
Environment Variables vs Configuration Files
Configuration data can also be stored in structured files like YAML, INI, JSON instead of environment variables. The approaches have tradeoffs:
Environment variables | Configuration files |
– Great for secrets | – Support complex data |
– Portable between processes | – Changes limited to applications restarts |
– Temp value overrides | – Better versioning/validation |
Use environment variables for:
- Secret keys, passwords, tokens
- System-level paths like $PATH
- Temporary overrides like debug flags
Prefer configuration files when you need:
- Structured/nested configuration data
- Dynamic reloads without app restarts
- Input validation
Common Environment Variables on Linux Systems
Many standard variables control shell and system behavior:
$HOME | Home directory path |
$PATH | Executable program search path |
$PWD | Present working directory |
$LANG | System language/locale |
$TERM | Terminal emulator type |
See a full list by running printenv or reading /etc/environment.
Best Practices
Follow these environment variable guidelines in Bash scripts:
- Always check if a variable is set before use
- Prefer default values over failing on unset variables
- Avoid global dependencies where possible
- Export variables only when necessary
- Give variables meaningful, self-documenting names
Adopting these practices will make scripts more robust, portable, and maintainable.
Conclusion
Properly handling environment variables is a key skill for writing production-grade Bash scripts on Linux. This guide covered critical techniques like:
- Checking if variables are defined with parameter expansion and exit codes
- Accessing values safely via ${} and command substitution
- Setting variable naming conventions and secure access controls
- Providing default values – with failsafe defaults applied at runtime
Learning how and when to leverage environment variables will level up your Bash scripting and general Linux admin skills. Refer to the external references below for even more in-depth guides on employing variables securely across processes with export and managing system-level configurations.
References
[1] Bash Environment Variable Guide[2] Storing Sensitive Data in Environment Variables
[3] How Processes Access Environment Variables
[4] Exporting Variables Safely Between Scripts