Home > Enterprise >  Continue while loop in Bash Script even if a condition fails
Continue while loop in Bash Script even if a condition fails

Time:10-20

#!/bin/bash
var="true"
i=1
while $var
do
  read -p "Enter value (true/false): " var
  if [[ $var == "true" ]]
  then
    echo "Iteration : $i"
    ((i  ))
  elif [[ $var == "false" ]]
  then
    echo "Exiting the process"
  elif [[ $? -eq 1 ]]
  then
    echo "Invalid Choice."
    echo "Avaialable Choices are true or false"
    exit
  fi
done

Script is Working Fine. I Enter true the loop will iterate for false the script stops. I want the script will continue asking "Enter Value" if any other value instead of true or false will be entered.

CodePudding user response:

This would do the same with a more academic syntax:

i=0
while :; do
  printf 'Enter value (true/false): '
  read -r var
  case $var in
    true)
      i=$((i   1))
      printf 'Iteration : %d\n' $i
      ;;
    false)
      printf 'Exiting the process\n'
      break
      ;;
    *)
      printf 'Invalid Choice.\nAvaialable Choices are true or false\n'
      ;;
  esac
done

CodePudding user response:

I'm new in bash. I tried that:

#!/bin/bash
i=1
while [[ $var != "false" ]]
do
    read -p "Enter value (true/false): " var
    if [[ $var == "true" ]]
    then
    echo "Iteration : $i"
    ((i  ))
    elif [[ $var == "false" ]]
    then
    echo "Exiting the process" 
    elif [[ $? -eq 1 ]]
    then
    echo "Invalid Choice."
    echo "Avaialable Choices are true or false"
    fi
done

I changed while $var with while [[ $var ]] because while works like if. It runs the given command. In there it is $var's value.

And I moved exit to first elif expression's end. So if user type false program will exit.

CodePudding user response:

You might find this to be a cleaner solution:

i=0
while true; do
  read -p "enter value: " myinput
  if [[ $myinput = true ]]; then
    echo "iteration $i"
    i=$((i 1))
  elif [[ $myinput = false ]]; then
    echo "exiting"
    exit
  else
    echo "invalid input"
  fi;
done;

The issue I see with your current code is that it is unclear which command's exit status $? refers to. Does it refer to the echo in the previous elif block? Or the last condition check? Or something else entirely?

  • Related