0

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?

0

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.