-2

I've got the basics of bash scripting (I think anyways), and i'm trying to move on to more advanced stuff.

I am trying to write a script that will perform input validation (the user must input either yes or no) and i'm trying to do this by combining a function and an if then else statement.

This is what i'm working on so far.

#!/bin/bash
func ()
{ 
    echo "Enter yes or no:"
    read var1
}

if [ $var1 != yes ] || [ $var1 != no ]
then
    func
else
    echo "I'm glag you said $var1"
fi

exit 0

I know that i'm using the wrong if then else operator/syntax, but I can't find the correct syntax threw googling.

I want it to run the function if var1 is either equal to yes or no, so the user can't input something else.

cuonglm
  • 150,973
  • 38
  • 327
  • 406
steve51516
  • 191
  • 1
  • 3
  • 10
  • 1
    Why `if` and not `while` to insist until the input is correct? – manatwork Mar 02 '14 at 17:20
  • If your script is complex enough to warrant careful input validation, it is certainly ripe for a real scripting language, like Python, Ruby, or Perl. – vonbrand Mar 02 '14 at 17:34
  • Agree with vonband. If you are doing something complex, try Python if it is available. Also, [avoid bashisms](http://unix.stackexchange.com/questions/24146/avoiding-bash-isms-in-shell-scripts). Use /bin/sh instead. – Gregor Mar 02 '14 at 18:14

2 Answers2

1

I think you have some wrong logic in your script. You should refer to X Tian's link in above comment to learn more about bash.

Here's a quick fix for you script:

func() {
  echo -n "Enter yes or no: "
  read var1
}

while true; do
  func

  if [[ $var1 == "yes" ]] || [[ $var1 == "no" ]]
  then
    printf "I'm glag you said %s\n" "$var1"
    break
  fi
done

exit 0
cuonglm
  • 150,973
  • 38
  • 327
  • 406
0
#!/bin/bash
func()
{
    echo -n "Enter yes or no : "

    read confirmation
}   
confirmation="$(echo ${confirmation} | tr 'A-Z' 'a-z')"
if [ "$confirmation" == yes ] || [ "$confirmation" == no ]; then
    echo "I am gladd you said $confirmation"
else
    func
fi
exit 0
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
klerk
  • 2,779
  • 2
  • 16
  • 15