I'm working on a shell script that does certain changes on a txt file only if it does exist, however this test loop doesn't work, I wonder why? Thank you!
while [ ! -f /tmp/list.txt ] ; do sleep 2 done
In Linux everything is a file. You can use the test command followed by the operator -f to test if a file exists and if it's a regular file. In the same way the test command followed by the operator -d allows to test if a file exists and if it's a directory.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With