The problem statement is that if a condition is not true, it should "stop" the for loop or should not progress unless that value is met.
Lets say that there is an input statement of true/false or a boolean statement in a for loop that prints to 1 to 10.
If the condition goes false in the the 5th iteration, it should stay at 5th iteration until the boolean returns true.
for i in {1..10}
do
read jobstatus
# echo $i
if [ "$jobstatus" = true ] ; then
echo 'Okay lets progress'
else
echo 'Nop, cant progress'
((i--))
# continue
#print $i
fi
echo $i
done
I have tried making codes such as this, also checked it via making files that were acting as "flags" But I cant seem to "stop" the progression. I dont want to break the loop, I just want to make it stay at that specific iteration until and unless the state changes. Like if the job status goes falses at i=5, i should stay at 5 unless jobstatus gets to true. ( I intend to check the jobstatus at each input)
With an interactive user input, Maybe something like this:
#!/bin/sh
i=0
while [ "$i" -le 10 ] && printf 'Enter status: '; do
IFS= read -r jobstatus
case "$jobstatus" in
true)
i=$((i+1))
printf 'Okay lets progress to %d' "$i";;
*)
printf >&2 'Nop, cant progress because jobstatus is: %s' "${jobstatus:-empty}"
esac
printf '\n'
done
Using a text file for the input, to test the script.
The file.txt
true
true
true
true
true
false
foo
bar
baz
true
true
true
true
qux
true
false
The script:
#!/bin/sh
i=0
while [ "$i" -le 10 ] && IFS= read -r jobstatus; do
case "$jobstatus" in
true)
i=$((i+1))
printf 'Okay lets progress to %d' "$i";;
*)
printf >&2 'Nop, cant progress because jobstatus is: %s' "${jobstatus:-empty}";;
esac
printf '\n'
done < file.txt
Output:
Okay lets progress to 1
Okay lets progress to 2
Okay lets progress to 3
Okay lets progress to 4
Okay lets progress to 5
Nop, cant progress because jobstatus is: false
Nop, cant progress because jobstatus is: foo
Nop, cant progress because jobstatus is: bar
Nop, cant progress because jobstatus is: baz
Nop, cant progress because jobstatus is: empty
Okay lets progress to 6
Okay lets progress to 7
Okay lets progress to 8
Okay lets progress to 9
Nop, cant progress because jobstatus is: qux
Nop, cant progress because jobstatus is: empty
Okay lets progress to 10
Nop, cant progress because jobstatus is: false