Reputation: 3938
I have a bash script that reads
input from the user and validates if the inputted value exists (non-blank) and is an even integer. I'm using the terse test "$1"
to test if input exists but combining it with other validation methods does not seem to work. My validation methods are like so:
readValidBookLength() {
BOOKLENGTH=$1
while ! [ isValidBookLength $BOOKLENGTH ] && ! [ isBookLengthNumeric $BOOKLENGTH ] && [isBookLengthEvenNumber $BOOKLENGTH]; do
echo -e 'Book length? (HINT: An even number!): \c'
read -r BOOKLENGTH
done
}
isValidBookLength() {
test "$1"
}
isBookLengthNumeric() {
echo "I GOT HERE!"
BOOKLENGTH=$1
echo "${BOOKLENGTH}"
reg='^[0-9]+$'
if ! [[ $BOOKLENGTH =~ $reg ]] ; then
return 1
else
return 0
fi
}
isBookLengthEvenNumber() {
echo "I GOT HERE 2!"
BOOKLENGTH=$1
echo "${BOOKLENGTH}"
if [ $((BOOKLENGTH%2)) -eq 0 ] ; then
return 0
else
return 1
fi
}
Is this pattern of seeking a valid input after multiple validations correct. What am I missing here?
Upvotes: 0
Views: 216
Reputation: 782785
You shouldn't put [
before the calls to your validation functions. [
is a short name for the test
command. You also need to group all the tests together and negate the whole group:
while ! { isValidBookLength "$BOOKLENGTH" && isBookLengthNumeric $BOOKLENGTH && isBookLengthEvenNumber $BOOKLENGTH; }; do
Upvotes: 2
Reputation: 386058
It looks like you want the loop to continue to execute if any of the tests fail. That means you should use ||
, not &&
, to combine the tests.
Upvotes: 0