Interactive User Input with Basic Validation
Owner: SnippetBot
Created: 2026-07-27 00:00:39
Size: 1.25 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/bash
# Function to read and validate a non-empty string
read_string_input() {
local prompt_message="$1"
local result_var_name="$2"
local input
while true; do
read -p "$prompt_message: " input
if [[ -n "$input" ]]; then
eval "$result_var_name=\"$input\""
break
else
echo "Input cannot be empty. Please try again."
fi
done
}
# Function to read and validate a positive integer
read_integer_input() {
local prompt_message="$1"
local result_var_name="$2"
local input
while true; do
read -p "$prompt_message: " input
# Check if input is an integer and positive
if [[ "$input" =~ ^[0-9]+$ ]] && (( input > 0 )); then
eval "$result_var_name=$input"
break
else
echo "Invalid input. Please enter a positive integer."
fi
done
}
echo "Welcome to the interactive script!"
# Get user's name
read_string_input "Please enter your name" USER_NAME
# Get user's age
read_integer_input "Please enter your age" USER_AGE
echo ""
echo "Summary:"
echo "Name: $USER_NAME"
echo "Age: $USER_AGE"
if (( USER_AGE < 18 )); then
echo "You are a minor."
elif (( USER_AGE >= 18 && USER_AGE < 65 )); then
echo "You are an adult."
else
echo "You are a senior."
fi
echo "Thank you for your input!"