LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   shell script to check availability of a file for 1 hour , after one hour if file not there , it will echo "Time Out" (https://www.linuxquestions.org/questions/linux-newbie-8/shell-script-to-check-availability-of-a-file-for-1-hour-after-one-hour-if-file-not-there-it-will-echo-time-out-4175671073/)

subir 03-09-2020 11:50 PM

shell script to check availability of a file for 1 hour , after one hour if file not there , it will echo "Time Out"
 
i wrote this code. but the problem is after every 300s it prints "Time over", when $fname present is got out from the loop. I want "time over" after 1hr if file not arrived, but after 300s it starts to print "time over"

#!/bin/bash
echo "enter file name"
read fname
START=`date +%s`
while [ $(( $(date +%s) - 3600 )) -lt $START ]; do
if [ -e $fname ]
then
echo "$fname present"
break
sleep 300
else
echo "Time Over"
fi
done

chrism01 03-10-2020 02:00 AM

This basically does what you want
Code:

file=time.t

now=$(date +%s)
end=$((now + 10))

found=0
while [[ $now -le $end ]]
do
        if [[ -e $file ]]
        then
                found=1
                echo "file found"
                break
        else
                sleep 3
        fi
        now=$(date +%s)
done

if [[ $found -eq 0 ]]
then
        echo "Not found"
fi

although you'll need to customise it a bit.

pan64 03-10-2020 02:01 AM

would be nice to use code tags, otherwise hard to read and understand your script. This looks much better:
Code:

#!/bin/bash
echo "enter file name"
read fname
START=`date +%s`
while [ $(( $(date +%s) - 3600 )) -lt $START ]; do
    if [ -e $fname ]
    then
        echo "$fname present"
        break
        sleep 300
    else
        echo "Time Over"
    fi
done

I hope you will now better understand what's happening.

subir 03-10-2020 02:22 AM

OMG. Thank you very much ...

MadeInGermany 03-10-2020 07:05 AM

If you really must have the echo in the loop, then a break must follow it:
Code:

#!/bin/bash
echo "enter file name"
read fname
END=$(( $(date +%s) + 3600 ))
while :
do
  if [ $(date +%s) -ge $END ]
  then
    echo "Time Over"
    break
  fi
  if [ -e "$fname" ]
  then
    echo "$fname present"
    break
  fi
  sleep 300
done

Unless the while loop is forced into a sub shell (e.g. by a pipe into it or from it),
it is better to query a variable after the loop:
Code:

#!/bin/bash
echo "enter file name"
read fname
END=$(( $(date +%s) + 3600 ))
found=""
while [ $(date +%s) -lt $END ]; do
  if [ -e "$fname" ]
  then
    echo "$fname present"
    found=1
    break
  fi
  sleep 300
done
if [ -z "$found" ]
then
  echo "Time Over"
fi



All times are GMT -5. The time now is 04:51 AM.