locations of an error message in the while loop with conditional statements

advertisements

This script checks for the existence of the file every 5 seconds for only 30 seconds.The script waits for the file to appear If it finds the file it echos “info: done waiting”.

The trouble I am having is with the error message after is exits after 30 seconds if the file is not found.

The way the script is configured the now the error timeout is printed after each loop.

#!/bin/bash
count=1
while [ $count -le  6 ]
do
    if [ ! -e /tmp/2007.txt ]
    then
       echo "info : sleeping for 5 seconds"
       (( count++ ))
    sleep 5
    elsif [ -e /tmp/2007.txt ]
    echo "info: done waiting"
    break
    fi
echo "error: timeout"
done

This is what I get (bad)

info : sleeping for 5 seconds
error: timeout
info : sleeping for 5 seconds
error: timeout
info : sleeping for 5 seconds
error: timeout
info : sleeping for 5 seconds
error: timeout
info : sleeping for 5 seconds
error: timeout
info : sleeping for 5 seconds
error: timeout

if i place it out of the loop - it works great

break
    fi

done
echo "error: timeout"

This is what i get

[email protected] ~ $ /tmp/wait_while
info : sleeping for 5 seconds
info : sleeping for 5 seconds
info : sleeping for 5 seconds
info : sleeping for 5 seconds
info : sleeping for 5 seconds
info : sleeping for 5 seconds
error: timeout
[email protected] ~ $

however if i touch the /tmp/2007.txt file - it breaks but the error timeout still shows up

[email protected] ~ $ /tmp/wait_while
info : sleeping for 5 seconds
info : sleeping for 5 seconds
info: done waiting
error: timeout

This is an easy question, but i am bringing it here to the community because it reflects a common problem that i have in understanding loops with conditional statements and where to place those statements. I come across this alot in my scripting and I need to understand this, I need to evolve. All i am looking for is the script to check for 30 seconds, and if it does not find anything to throw out a error message. If the script finds the file, i want it to let me know and NOT kick out the error message.


You can check after the while loop whether the file was found or not before displaying the error message.

#!/bin/bash 

found=0
count=1
while [ $count -le  6 ]
do
    if [ ! -e /tmp/2007.txt ]
    then
       echo "info : sleeping for 5 seconds"
       (( count++ ))
       sleep 5
    else
      echo "info: done waiting"
      found=1
      break
    fi
done

if [ ! $found ]
then
   echo "error: timeout"
fi