Home > Back-end >  bash: while loop going to infinite loop while case statement
bash: while loop going to infinite loop while case statement

Time:04-15

This is my below bash script

#!/bin/bash
verify()
{
  while true ;do
      read -p "Have you fixed  ? Yes/No: " yn
      case $yn in
         YES|Yes|yes|y|Y)
         printf "Hola"
         check_status
         break
         #continue
         ;;
         NO|No|no|n|N)
         printf "Please fix"
         ;;
         *)
         printf "Please answer yes or no.\n"
         ;;
     esac
  done
}

check_status()
{
  while IFS=" " read -r rec1 rec2
  do
  if [ $rec2 == 'up' ]
  then
    echo "$rec1 is up"
  else
    echo "$rec1 is down so please fix"
    verify
  fi
  done < <(cut -d " " -f1,2 compute_list)
}


check_status

and my compute list is

abcd up
efgh down
..

And it is always giving

It is not showing the line

Have you fixed ? Yes/No:

But it is showing the below infinetely

Please answer yes or No? Please answer yes or No?

infinite loop it is showing same messages again and again and again

Any help

CodePudding user response:

Your outer function has redirected standard input to read from the cut process substitution, so that's where read is reading its input from.

Perhaps use a separate file descriptor for the process substitution.

Furthermore, your verify function recursively calls check_status again; probably take that out!

verify()
{
  while true ;do
      read -p "Have you fixed? Yes/No: " yn
      case $yn in
        YES|Yes|yes|y|Y)
         echo "Hola"
         # check_status # DON'T!
         break
         ;;
        NO|No|no|n|N)
         echo "Please fix"
         ;;
        *)
         echo "Please answer yes or no."
         ;;
     esac
  done
}
 
check_status()
{
  # Notice read -u 3 to read from fd3
  # Notice _ to read fields 3 and up
  while IFS=" " read -u 3 -r rec1 rec2 _
  do
    # Syntax: single =, add quoting
    if [ "$rec2" = 'up' ]
    then
      echo "$rec1 is up"
    else
      echo "$rec1 is down so please fix"
      verify
    fi
  # Notice 3<
  done 3< compute_list
}
 
check_status

I also took the liberty to fix your indentation and avoid the unnecessary process substitution; read can perfectly well read and discard the fields after the second.

printf is more versatile than echo but in this case, when you simply want to output static strings, I switched to echo.

Demo: https://ideone.com/pVerFm (I left in the process substitution there in case you want to see what it looks like syntactically.)

  • Related