Do not understand why my while loop fail (bash)

Hi again :slight_smile:
I still need your help now...

#!/bin/bash

SIZE=`ls -s text.txt`

while [ "$SIZE" != '0 text.txt' ]
do
[ my intructions ]
done

My problem is that the line "while ..." still print the same value after the first loop.
In [ my instruction ] one instruction change the size of text.txt
I've run my bash script in debug mode, and the problem is not here...

Can you help me please ?

Thanks :wink:

Hi.

It will always print the same value. You set the variable "SIZE" before the loop, and never update it.

You can apply the same logic here, as in your previous post.

i.e.

while test -s somefile.txt; do
  file is not empty...
done

You also didn't listen about quoting your variable, as was mentioned in your previous post.

Sorry about the quotes :wink:

I don't understand, my SIZE variable isn't executed when my script come back to the while line ?

I can't put the line SIZE =` ls -s text.txt` after the while because it will not work.
Shloud I have to update my SIZE variable in the end of the script, just before the done ?
I write basic bash script since yesterday, I have not done such thing yet

Hi.

I think what I was trying to say is, you don't need to execute the ls command to find out if a file is empty, or not.

the -s test option can do that for you.

See the man page for test.

Using some posixsh:

# number of chars in file
size=$(cat file | wc -c)
while ((size>0))
do
      do_something
      # look again
      size=$(cat file | wc -c)
done

Is same as scottn has written, using test command: is the file empty

while [ -s file ]
do
      do_something
done

Am assuming that initially this file is not blank but you want to do something within the loop which will make it blank at the last.

If my assumption is correct then below mentioned code can help you in this.

 
echo "Hi" > test_file
while [ -s test_file ]
do
echo "In while loop"
echo "Doing something - assuming that you will make test_file blank withing the loop itself"
echo "Creating test_file of 0 bytes so that this loop can be stopped."
rm test_file
touch test_file
done

---------- Post updated at 12:43 PM ---------- Previous update was at 12:34 PM ----------

Is this what you were looking for or you wanted something else?

Or if you are waiting for a file to exist and contain some data:

while true
do
        if [ -s test.txt ]
        then
                echo "my instructions"
                break
        else
                # Wait a reasonable time before trying again
                sleep 5
        fi
done