Reputation: 115
how to proceed in the script if file exists?
#!/bin/bash
echo "Start"
# waiting to be exist file
echo "file already exists, continuing"
Upvotes: 3
Views: 5531
Reputation: 531125
There are OS-specific ways to perform blocking waits on the file system. Linux uses inotify
(I forget the BSD equivalent). After installing inotify-tools, you can write code similar to
#!/bin/bash
echo "Start"
inotifywait -e create $FILE & wait_pid=$!
if [[ -f $FILE ]]; then
kill $wait_pid
else
wait $wait_pid
fi
echo "file exists, continuing"
The call to inotifywait
does not exit until it receives notification from the operating system that $FILE
has been created.
The reason for not simply calling inotifywait
and letting it block is that there is a race condition: the file might not exist when you test for it, but it could be created before you can start watching for the creation event. To fix that, we start a background process that waits for the file to be created, then check if it exists. If it does, we can kill inotifywait
and proceed. If it does not, inotifywait
is already watching for it, so we are guaranteed to see it be created, so we simply wait
on the process to complete.
Upvotes: 3
Reputation: 289675
Do a while
if a sleep X
, so that it will check the existence of the file every X seconds.
When the file will exist, the while
will finish and you will continue with the echo "file already exists, continuining"
.
#!/bin/bash
echo "Start"
### waiting to be exist file
while [ ! -f "/your/file" ]; # true if /your/file does not exist
do
sleep 1
done
echo "file already exists, continuing"
And goes instead of checking the file existence check if the script has already completed the background?
Based on the code you posted, I did some changes to make it work completely:
#!/bin/bash
(
sleep 5
) &
PID=$!
echo "the pid is $PID"
while [ ! -z "$(ps -ef | awk -v p=$PID '$2==p')" ]
do
echo "still running"
sleep 1
done
echo "done"
Upvotes: 4
Reputation: 115
To fedorqui: Is it so good? There is a problem?
#!/bin/bash
(
..
my code
..
) &
PID=$BASHPID or PID=$$
while [ ! ps -ef | grep $PID ]
do
sleep 0
done
Thank you
Upvotes: 0