Course contentsShow
← Linux
Lesson 177 of 1,8192. Deep Dive into Bash ScriptingFree lesson

User Input Sanitization

Prevent command injection vulnerabilities by validating all external input.

In this lesson, you will learn how to protect your scripts from "command injection" by strictly controlling how external data interacts with your system commands.

The Danger of Untrusted Input

When you write a script that accepts input—whether from an argument, a file, or a user prompt—it is tempting to pass that variable directly into a command. However, if that input contains shell metacharacters (like ;, &, or |), an attacker could terminate your intended command and start a new, malicious one.

For example, imagine a script that pings an IP address provided by a user:

# DANGEROUS CODE
read -p "Enter IP to ping: " user_ip
ping -c 1 $user_ip

If a user enters 8.8.8.8; rm -rf /, your script will ping the IP and then attempt to delete your files. This happens because the shell interprets the semicolon as a command separator.

Sanitizing with Pattern Matching

To prevent this, you must treat user input as data, not as executable code. The most reliable way to do this is to validate the input against a strict "allow-list" of expected characters before using it.

Using the Complex Pattern Matching techniques you learned earlier, you can force the input to match a specific format, such as a standard IPv4 address:

read -p "Enter IP to ping: " user_ip

# Validate: Only allow numbers and dots
if [[ ! "$user_ip" =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]]; then
    echo "Error: Invalid input format."
    exit 1
fi

# Now it is safe to use
ping -c 1 "$user_ip"

Defensive Best Practices

  1. Quote your variables: Always wrap variables in double quotes ("$user_ip") to prevent word splitting.
  2. Strict Validation: Use regular expressions to ensure the input contains only what you expect. If you expect a filename, ensure it doesn't contain path traversal characters like ../.
  3. Principle of Least Privilege: If a script doesn't need to run as root, never grant it those permissions. Even if sanitization fails, the damage is contained.

Key Takeaway: Never trust user input; always validate the format of external data against a strict allow-list before passing it to any system command.