0

dear community, I faced the problem that I can't break the while loop in this example. This script should output how many files are in the folder and when this count will be 0 do another step. But, when I'm executing the script and after deleting file/files from the folder the loop fails to meet the condition and continue working. Mb I'm doing something wrong because I'm the newest in the bash scripting. Will be appreciate your advice

var=$(ls some_folder/ | wc -l )
echo "$var"

while [ $var != 0 ];
do
    sleep 2
    echo "$test"
done

echo "finish!"
2
  • You're setting the value of var once, before the loop starts. It never changes inside the loop. You need to assign a new value for it inside the loop.
    – ilkkachu
    Aug 25, 2022 at 18:55
  • @ilkkachu, I got it, thank you so much:) Aug 25, 2022 at 20:03

1 Answer 1

0

You have composed an infinite loop. Presuming that the output of ls in your case is more than zero lines you effectively have:

var=1
while [ $var != 0 ]; do
    sleep 2
    echo "$test"
done

Since the value of var is never modified over the course of the loop, it will either run the body of the loop zero times or until the script is extrinsically terminated.

I should also point out that you are using a string comparison to do what is presumably supposed to be a numerical comparison. You should be using -ne rather than != for a numerical comparison.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .