I am trying to build loop for the user input until I get a specific input for example I want to stop the loop when the input = 4 and print siiiiii but the problem is the program stuck in the loop how can I set a new value for the loop input ?
#!/bin/bash
value=4
echo Enter the number:
read $input
while [ $input != $value ]
do
echo "The input must be between 1 and 4"
read input2
input = $input2
done
echo siiiiiiiiiiiiiiiiiii
CodePudding user response:
#!/bin/bash
value=4
echo Enter the number:
while read input; do
if [ "$input" = "$value" ]; then break; fi
echo "The input must be between 1 and 4" >&2
done
echo siiiiiiiiiiiiiiiiiii
You could also write:
while read input && [ "$input" != "$value" ]; do
echo "The input must be between 1 and 4" >&2
done
You might prefer to use -eq
and -ne
since you are doing integer comparisons, as this gives you additional error messages. Whether or not those error messages are useful is a design decision:
while read input && ! [ "$input" -eq "$value" ]; do
echo "The input must be between 1 and 4" >&2
done
The 4 main issues with your original code are: failure to quote variables, incorrect attempt at the assignment input = $input2
(you cannot have space around the =
), incorrect use of $
in the read $input
command, and failure to use the standard while read varname
idiom. There are probably some other minor issues as well, but those jump out.