While loop to test if a file exists in bash
I had the same problem, put the ! outside the brackets;
while ! [ -f /tmp/list.txt ];
do
echo "#"
sleep 1
done
Also, if you add an echo inside the loop it will tell you if you are getting into the loop or not.
I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.
I found that if I ran cat /tmp/list.txt
the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1;
just before the cat /tmp/list.txt
it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.
My final code:
while [ ! -f /tmp/list.txt ];
do
sleep 1;
done;
sleep 1;
cat /tmp/list.txt;
Hope this helps save someone a frustrating half hour!
If you are on linux and 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 introduced by sleep while still polling every "x" seconds. You can add more events if you anticipate that they are needed.
When you say "doesn't work", how do you know it doesn't work?
You might try to figure out if the file actually exists by adding:
while [ ! -f /tmp/list.txt ]
do
sleep 2 # or less like 0.2
done
ls -l /tmp/list.txt
You might also make sure that you're using a Bash (or related) shell by typing 'echo $SHELL'. I think that CSH and TCSH use a slightly different semantic for this loop.