In this lesson, you will learn how to protect your scripts from malicious or unexpected input by normalizing and validating the data provided through positional parameters.
The Danger of Untrusted Input
When you write a script that accepts arguments (like $1, $2), you are inviting the outside world to interact with your code. If you trust these inputs blindly—for example, passing them directly into a command like rm or grep—you risk anything from accidental data loss to severe security vulnerabilities like command injection. Positional Parameter Sanitization is the practice of treating all incoming arguments as "guilty until proven innocent."
Normalization and Validation
Before your script performs any "heavy lifting," it should verify that the arguments meet your expectations. This is done in two stages:
- Normalization: Converting input into a standard format. For example, if you expect a "yes/no" answer, you might convert the input to lowercase so that
Yes,YES, andyesare all treated asyes. - Validation: Checking if the input is safe and logical. Does the input contain only numbers? Is it an existing file path?
Consider this example where we expect a simple directory name:
#!/bin/bash
# Expects a directory name as $1
TARGET_DIR="$1"
# 1. Normalization: Remove trailing slashes
TARGET_DIR="${TARGET_DIR%/}"
# 2. Validation: Check if it's a directory and isn't empty
if [[ -z "$TARGET_DIR" ]]; then
echo "Error: No directory provided."
exit 1
fi
if [[ ! -d "$TARGET_DIR" ]]; then
echo "Error: '$TARGET_DIR' is not a valid directory."
exit 1
fi
echo "Proceeding with operations in $TARGET_DIR..."
By assigning $1 to a variable and checking it against a strict condition, you create a "sandbox" for your data. If the input doesn't match your criteria, your script exits safely before executing any dangerous commands. This prevents a user from passing a malicious string, such as ; rm -rf /, because your validation logic will reject it long before the shell tries to interpret it as a command.
Key Takeaway: Never pass positional parameters directly into internal logic; always validate their format and content to ensure they conform to your script's requirements before processing.