Home > Software design >  Linux Bash - Stuck in while loop
Linux Bash - Stuck in while loop

Time:10-22

I have made a small "game" where I have if statements inside a case inside a while loop. The case and if statements work as I intended, but I want the while loop to end when a, b and c equals to 1. I have tried lots of conditions in the while loop, and different ways to write it, but it will not work. Please help!

#!/bin/bash
a=0
b=0
c=0
echo "The engine is broken! You have to fix it!"
#sleep 2
echo "In front of you lies an angle grinder, a ratchet and a screwdriver."
#sleep 2
echo "It appears to be a metal rod blocking the engine from turning. There is also a screw loose, and a bolt that needs to be tightened."
#sleep 4

while [[ [$a != 1] && [$b != 1] && [$c != 1] ]]; do
read -rep $'Which tool do you choose? (A for Angle Grinder, R for Ratchet and S for Screwdriver)\n' ars
    case $ars in
        [aA] ) if [ $a == 0 ]; then
                    echo "You use the angle grinder to cut the metal rod. The motor looks like it can turn now.";
                    a=1;
                else
                    echo "It looks like you already have cut the metal rod. Try another tool.";
                fi;;
        [rR] ) if [ $b == 0 ]; then
                    echo "You use the ratchet to tighten the bolt. It looks tight now.";
                    b=1;
                else
                    echo "It looks like you already have tightened the bolt. Try another tool.";
                fi;;
        [sS] ) if [ $c == 0 ]; then
                    echo "You use the screwdriver to tighten the screw. The screw looks tight.";
                    c=1;
                else
                    echo "It looks like you already have tightened the screw. Try another tool.";
                fi;;
        * ) echo "Try A, R or S";;
    esac
    printf "$a, $b, $c\n"
done

read -p "The engine is fixed! Press enter to turn it on!"
echo "The engine is running! A vent appears to be opened!"

CodePudding user response:

while [[ [$a != 1] && [$b != 1] && [$c != 1] ]]; do

This has no realistic meaning.

See for example my previous answer to someone with a similar misconception.

In short, while "argument" is a command. It runs that command, and then whatever is between do and done, as long as that command does not fail (does not return a non-zero exit-code).

And [[ is a command (a built-in one), exactly as ls or awk. Sometime it fails sometimes it succeeds (exit code non-zero or zero). And it does so depending on its arguments (it is a command, whose purpose is to fail or not)

  •  Tags:  
  • bash
  • Related