discard accidental input before read
#!/bin/bash
# NOTE: didn't use BATS framework due to interactive usage
## Test 1: read_safe() does discards unwanted characters and affects outer scope
test_read_safe_affects_outer_scope() {
# variable in outer scope
local x=0
# unwanted input
echo "please enter random unwanted lines of characters within 5 seconds:"
sleep 5
read_safe x "please enter 11 for x value"
# test
if (( x == 11 )); then
echo "$(date +%T) [INFO] test_read_safe_affects_outer_scope OK!"
echo ""
else
echo "$(date +%T) [ERROR] Bad x value: $x"
echo "$(date +%T) [ERROR] test_read_safe_affects_outer_scope Failed!"
exit 1
fi
}
test_read_safe_affects_outer_scope
## Test 2: read_safe() affects the closest outer scope only
# create an intermediate scope
read_safe_innerscope() {
# inner scope x
local x=1
# do
echo "$(date +%T) [DEBUG] inner x value before read_safe(): $x"
read_safe $1 "$2"
echo "$(date +%T) [DEBUG] inner x value after read_safe(): $x"
}
# outermost scope executing read_safe()
test_read_safe_closest_outer_scope_only() {
# outer scope x
local x=0
# unwanted input
echo "please enter random unwanted lines of characters within 5 seconds:"
sleep 5
# do
echo "$(date +%T) [DEBUG] outer x value before read_safe(): $x"
read_safe_innerscope "x" "please enter 11 for x value"
echo "$(date +%T) [DEBUG] outer x value after read_safe(): $x"
# test
if (( x == 0 )); then
echo "$(date +%T) [DEBUG] test_read_safe_closest_outer_scope_only OK!"
else
echo "$(date +%T) [ERROR] Bad x value: $x"
echo "$(date +%T) [ERROR] test_read_safe_closest_outer_scope_only Failed!"
exit 1
fi
}
test_read_safe_closest_outer_scope_only
read_safe() {
#
# discard accidental input before read.
#
# parameters
# $1 variable name to read into
# $2 prompt
echo "$(date +%T) [DEBUG] read_safe(\"$1\" \"$2\") begins..."
local __discarded
# check number of arguments
if (( $# != 2 )); then
echo "$(date +%T) [ERROR] Wrong argument count: $#"
exit 1
fi
# discard unwanted characters
echo "$(date +%T) [DEBUG] discarding unwanted characters...."
read -N 100000 -t 0.01 __discarded
# read (non-local)
read -p "***USER INPUT*** $2:" "$1"
echo "$(date +%T) [DEBUG] read_safe(\"$1\" \"$2\") done!"
}