0

I was reading all of the posts about if statements but not of them seem to solve my issue. I'm writing a shell script and I need to validate the user's input for an operation (addition, subtraction, division). My code is as follows:

valid_operator(){
  if [[ "$operator" != "+"  ||  "$operator" != "-" || "$operator" != "/"]]; then
   echo "Sorry, $operator, ++ is not a valid operator. Please re-enter valid operator"
   main
  fi
}
4
  • 1
    Space missing before ]].
    – choroba
    Oct 19, 2020 at 8:36
  • 1
    And what happens when you run this? Do you get an error message? What is it? As choroba said, you have a syntax error, so you should be getting an error. Do you not?
    – terdon
    Oct 19, 2020 at 8:40
  • 2
    What does main do in your code?
    – Kusalananda
    Oct 19, 2020 at 11:39
  • @Kusalananda main wraps another class (cal_val: calculates the value the user input) in a while loop so it continuously loops until the user inputs X as the exit condition. This class is wrapped in cal_val to continuously check if the operator entered is valid. (this is my first unix script pls be gentle)
    – Xander
    Oct 30, 2020 at 0:04

1 Answer 1

1

I think it's just a syntax error due to a missing space before the ]], and IIUC you want true if $operator is NONE of the values tested? I tested the if-then part & this should work.

valid_operator(){
  if [[ "$operator" != "+"  &&  "$operator" != "-" && "$operator" != "/" ]]; then
    echo "Sorry, $operator, ++ is not a valid operator. Please re-enter valid operator"
    main
  fi
}

A 3-input XOR gate :)

3
  • 2
    The function also does not return anything related to whether the operator is valid or not, and presumably, the call to main would be a recursive call. The flow of control through this script may have to be revisited.
    – Kusalananda
    Oct 19, 2020 at 8:58
  • @Kusalananda: I'm sure you're correct, but I've no info on what he's doing beyond the evaluation of $operator.
    – Seamus
    Oct 19, 2020 at 9:02
  • Thank you for your comment, it worked. I got confused by the gates silly me.
    – Xander
    Oct 30, 2020 at 0:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .