While the loop checks if the file exists in bash

I am working on a shell script that makes certain changes to the txt file only if it exists, but this test loop does not work, I wonder why? Thank!

while [ ! -f /tmp/list.txt ] ; do sleep 2 done 
+48
bash shell
Mar 04 '10 at 14:09
source share
5 answers

When you say "does not work," how do you know that it does not work?

You can try to find out if the file exists by adding:

 while [ ! -f /tmp/list.txt ] do sleep 2 done ls -l /tmp/list.txt 

You can also make sure that you are using a Bash (or related) shell by typing 'echo $ SHELL'. I think that CSH and TCSH use slightly different semantics for this loop.

+75
Mar 04 '10 at 14:17
source share

If you have inotify tools installed, you can do this:

 file=/tmp/list.txt while [ ! -f "$file" ] do inotifywait -qqt 2 -e create -e moved_to "$(dirname $file)" done 

This reduces the delay caused by sleep while still checking every 2 seconds. You can add more events if you expect them to be needed.

+37
Aug 6 2018-11-18T00:
source share

I had the same problem, set it! out of brackets;

 while ! [ -f /tmp/list.txt ]; do echo "#" sleep 1 done 

Also, if you add an echo inside the loop, it will tell you whether you get into the loop or not.

+2
Jan 11 '16 at 15:54
source share

I ran into a similar problem and it brought me here, so I just wanted to leave my solution for those who are experiencing the same.

I found that if I ran cat /tmp/list.txt , the file would be empty, although I was sure that the contents were immediately placed in the file. It turns out if I put sleep 1; just before cat /tmp/list.txt , it worked as expected. There should have been a delay between the time the file was created and the time it was written, or something in that direction.

My last code is:

 while [ ! -f /tmp/list.txt ]; do sleep 1; done; sleep 1; cat /tmp/list.txt; 

Hope this helps save someone a disappointing half hour!

0
Sep 16 '14 at 17:18
source share

do it like that

 while true do [ -f /tmp/list.txt ] && break sleep 2 done ls -l /tmp/list.txt 
-four
Mar 04 '10 at 14:34
source share



All Articles