BASH
Get Interactive User Input with Validation
Learn to prompt users for input in Bash scripts, including basic validation for non-empty strings or numeric values, making your scripts more interactive.
#!/bin/bash
# Function to get non-empty string input
get_string_input() {
local prompt_msg="$1"
local var_name="$2"
local input_val=""
while true; do
read -p "$prompt_msg: " input_val
if [ -n "$input_val" ]; then
eval "$var_name=\"$input_val\""
break
else
echo "Input cannot be empty. Please try again."
fi
done
}
# Function to get numeric input
get_numeric_input() {
local prompt_msg="$1"
local var_name="$2"
local input_val=""
while true; do
read -p "$prompt_msg: " input_val
# Check if input is a valid integer (positive or negative)
if [[ "$input_val" =~ ^-?[0-9]+$ ]]; then
eval "$var_name=$input_val"
break
else
echo "Invalid input. Please enter a number."
fi
done
}
# Example Usage:
echo "--- User Profile Setup ---"
USER_NAME=""
get_string_input "Enter your name" USER_NAME
echo "Hello, $USER_NAME!"
USER_AGE=0
get_numeric_input "Enter your age" USER_AGE
echo "You are $USER_AGE years old."
CONFIRMATION=""
read -p "Are you sure this information is correct? (yes/no): " CONFIRMATION
if [[ "$CONFIRMATION" =~ ^[Yy][Ee][Ss]$ ]]; then
echo "Information confirmed. Script proceeding..."
else
echo "Information not confirmed. Exiting."
exit 1
fi
How it works: This script provides functions to solicit and validate user input. `get_string_input` ensures a non-empty string is provided, re-prompting until valid. `get_numeric_input` checks if the input is a valid integer using a regex pattern. The `read -p` command displays a prompt, and the input is stored in the specified variable. Basic `if` and `[[ =~ ]]` statements are used for validation and branching.