Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop to test if a file exists in bash

Tags:

bash

shell

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 
like image 666
Zenet Avatar asked Mar 04 '10 14:03

Zenet


People also ask

How do you check if a file exists in a directory in Linux?

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.


2 Answers

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.

like image 97
CWF Avatar answered Sep 28 '22 05:09

CWF


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.

like image 22
yingted Avatar answered Sep 28 '22 07:09

yingted