How to Concisely Check Environment Variables in a Unix Shell Script?
When writing shell scripts, you often need to ensure specific environment variables are set. This avoids unexpected behavior or errors during script execution. Here are some concise and elegant ways to perform such checks.
Traditional Approach: Individual Checks
The classic method involves checking each variable individually:
if [ -z "$STATE" ]; then
echo "Need to set STATE"
exit 1
fi
if [ -z "$DEST" ]; then
echo "Need to set DEST"
exit 1
fi
While straightforward, it becomes verbose when you have many variables to check.
Parameter Expansion: Portable and Elegant
The ${var:?message}
syntax provides a concise way to enforce that a variable is set (and optionally non-empty):
: "${STATE:?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"
If $STATE
is unset or empty, the shell prints Need to set STATE
and exits. Replace :
with any valid command (e.g., echo
) if you need custom behavior. The :
command evaluates the expression but does nothing else, making it lightweight.
Always wrap variables in double quotes to avoid issues with special characters or globbing:
: "${STATE:?Need to set STATE}"
Handling Multiple Variables
For scripts requiring multiple variables to be checked, use a loop:
for var in STATE DEST PATH_TO_FILE; do
: "${!var:?Need to set $var}"
done
This dynamically evaluates each variable in the list. The loop simplifies checks for a list of required variables.
Compact Inline Syntax
For quick checks, use inline commands with &&
or curly braces:
[ -z "$STATE" ] && { echo "Need to set STATE"; exit 1; }
[ -z "$DEST" ] && { echo "Need to set DEST"; exit 1; }
This is compact and easy to read, making it suitable for simpler scripts.
Distinguishing Between Unset and Empty Variables
Sometimes, distinguishing between “unset” and “empty” variables is important. Use [ -v VAR ]
(in bash
4.2+) to check if a variable is set, and [ -z "$VAR" ]
to check if it’s empty:
if [ -v STATE ]; then
[ -z "$STATE" ] && echo "STATE is empty" && exit 1
else
echo "STATE is not set"
exit 1
fi
These methods improve script readability and maintainability while keeping the logic robust.
Labels: How to Concisely Check Environment Variables in a Unix Shell Script?
0 Comments:
Post a Comment
Note: only a member of this blog may post a comment.
<< Home