Linux Basic — Input Validation Loops
Input Validation Loops
Interactive scripts must validate everything. A robust loop re-prompts until valid input or a retry limit is reached.
Pattern: retry with default
max_retries=3
retries=0
while true; do
read -rp "Port [8080]: " port
port=${port:-8080}
if [[ "$port" =~ ^[0-9]+$ ]] && (( port >=1 && port <= 65535 )); then
break
fi
((retries++)) || true
if (( retries >= max_retries )); then
echo "too many attempts" >&2; exit 1
fi
echo "Please enter a valid port (1-65535)" >&2
done
# use $port
Always normalise the input (${var:-default}), validate, and copy to a safe variable.
Trim whitespace
trim() { printf '%s' "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' ; }
input=$(trim "$input")
Use read -r to avoid backslash magic.
Safe yes/no with defaults
confirm() {
local prompt default reply
prompt="$1"; default="$2"
while true; do
read -rp "$prompt" reply
reply=${reply:-$default}
case "${reply,,}" in
y|yes) return 0;;
n|no) return 1;;
*) echo "Please answer yes or no.";;
esac
done
}
if confirm "Delete all files? [y/N] " "n"; then
echo "deleting"
fi
case "${reply,,}" lowercases the answer (Bash-only). Use tr '[:upper:]' '[:lower:]' for POSIX.
Limit retries and provide an escape
- Offer a
qto quit - Use a timeout to resume with a default
- Log invalid attempts for audit if needed
Next → select Statement