I have a bash script that creates a file with a timestamp as the name. Once some time passes, it is supposed to pick up that file and do something with it. I want it to pick it up after two hours, but for some reason, it is picking it up after 57 minutes (and 6 seconds). Can anyone point me to an error in my logic or assumptions?
Here are the details:
I have a variable set to 2 hours (7200 seconds):
SERVICE_DURATION=${SERVICE_DURATION:-7200} # seconds
I am setting the filename equal to the Unix timestamp concatenated with nanoseconds:
active_name=`date +%s%N`
echo "${1}" >> ${ACTIVE_DIR}/${active_name}
I then loop forever until the time is right:
while true
do
for fa in ${ACTIVE_DIR}/*
do
if [ $(basename ${fa}) -le $(($(date +%s%N) - ${SERVICE_DURATION} * 1000000000)) ]
then
exec 6< "${fa}"
read old_port <&6
read old_host <&6
read old_config <&6
exec 6<&-
logger -p daemon.info "Recycling port ${old_port}."
start_remote_service "${old_port}"
stop_remote_service "${old_port}" "${old_host}" "${old_config}" "${fa}"
sleep 2
fi
done
sleep 30
done
I can't see what is wrong with this. The filename ($(basename ${fa})) shouldn't be less than the current time minus the specified duration in nanoseconds ($(($(date +%s%N) - ${SERVICE_DURATION} * 1000000000))) until the duration has passed.
In order to keep the script from constantly checking, there is a sleep 30 at the end of the loop, so it could be that the time is somewhere between 56:36 and 57:06.
Any help would be appreciated. Thanks.
Related
I am trying to write a simple script that helps me estimate the time left in an entry queue. So far I have gotten this, but it seems to deliver entirely random results, especially as the time in queue gets longer, or the position gets closer to zero.
To clarify, the script prompts for the initial position 'inum' whenever the queue moves, the user is prompted to enter the current place in queue. (There is no constant movement) I wanted to calculate the time until entry by taking the current place in queue, comparing it to the total amount of people, and then use the elapsed time in queue as a means to estimate a remaining time (+ a 5 Minute grace period). However, this gives me very inconsistent results.
#!/bin/sh
read -p "Users in queue: " inum;
echo ""
n=$inum
t0=$(date +%s)
while true; do
read -p "Users in queue: " nleft;
t=$(date +%s)
d=$((t - t0))
cal=$(echo "((($d * $nleft / ($n - $nleft)) - $d) / 60) + 5" | bc)
echo "Time in queue: $((d / 60)) Minutes."
echo "Approximate time left: $cal Minutes."
echo ""
done
echo "End."
with time command, use
time yourscript.sh
or with
start=`date +%s`
read -p "Users in queue: " nleft; #into while
end=`date +%s`
caltime=$( echo "$end - $start" | bc -l )
I need difference between two dates in seconds. I input datetime in format "YYYY-MM-DD HH:MM" and then calculate difference in seconds, but the run_time is in UTC timezone and current_time is calculated from system timezone.
#!/bin/bash
run_time=$1
run_time=$(date -d "$run_time" +"%s")
current_time="$(date +"%s")"
echo $run_time
echo $current_time
echo "$(($run_time-$current_time))"
How to retrieve absolute value of seconds between current datetime and another one?
Edit: actually that script has worked after restart of computer. No clue why previously it showed up different results. I have not changed anything in settings, nor computer time.
Right #Jetchisel, based on your comment a sample script could look like:
#!/bin/bash
STARTTIME_UTC=$1
STARTTIME_UTC=$(date -u -d "${STARTTIME_UTC}" +"%s")
echo "CURRENT DATE: $(date)"
CURRENTTIME="$(date +"%s")"
echo
echo "STARTTIME_UTC: ${STARTTIME_UTC} sec since"
echo "CURRENTIME: ${CURRENTTIME} sec since"
echo
echo "RUNTIME: $((${CURRENTTIME}-${STARTTIME_UTC})) sec"
As per original question
I input datetime in format "YYYY-MM-DD HH:MM"
the value of input time seconds in ${STARTTIME_UTC} will be set to zero (:00) whereby the value of current time seconds in ${CURRENTIME} will be set to what the clock provides. I.e., if it is 18 seconds before the next minute and the runtime would be almost zero, the script will report a difference of 42 seconds.
We have a 15 year (or so) old script we are trying to figure out and document. We have found some errors in it but one specific log file gives us much headache. and I would love some help figuring it out.
First the function that are run with the question:
#=========================================================#
# Define function removeOldBackupFile. #
#=========================================================#
removeOldBackupFile()
{
#set -x
echo "Removing old backups if they exists." >> "${report}"
local RCLOC=0
spaceBefore=$(getAvailableSpace ${backupDirectory})
timesToWait=60 # Wait a maximum of 10 minutes before bailing
cat ${oldDbContainer} | while read fileName
do
echo "Old file exists. Removing ${fileName}." >> "${report}"
removeFileIfExist "${fileName}"
RC=$?
echo "Resultcode for removing old backup is: RC=$RC." >> "${report}"
RCLOC=$(($RC+$RCLOC))
spaceAfter=$(getAvailableSpace ${backupDirectory})
# Wait for the OS to register that the file is removed
cnt=0
while [ $spaceAfter -le $spaceBefore ]; do
cnt=$((cnt+1))
if [ $cnt -gt $timesToWait ]; then
echo "Waited too long for space in ${backupDirectory}" | tee -a "${report}"
RCLOC=$(($RCLOC+1))
return $RCLOC
fi
sleep 10
spaceAfter=$(getAvailableSpace ${backupDirectory})
done
done
return $RCLOC
}
The place where this function is ran looks as follows:
#=========================================================#
# Remove old backupfiles if any exist. #
#=========================================================#
removeOldBackupFile
RC=$?
RCSUM=$(($RC+$RCSUM))
We have identified that the if condition is a bit wrong and the while loops would not work as intended if there are multiple files.
But what bothers us is output from a log file:
...
+ cnt=61
+ '[' 61 -gt 60 ']'
+ echo 'Waited too long for space in /<redacted>/backup'
+ tee -a /tmp/maintenanceBackupMessage.70927
Waited too long for space in /<redacted>/backup
+ RCLOC=1
+ return 1
+ return 0
+ RC=0
+ RCSUM=0
...
As seen in the log output after the inner loop have ran 60 times and ending it returns 1 as expected.. BUT! it also have return 0 after!? Why is it also returning 0?
We are unable to figure out the double returns... Any help appriciated
The first return executes in the subshell started by the pipe cat ${oldDbContainer} | while .... The second return is from return $RCLOC at the end of the function. Get rid of the useless use of cat:
removeOldBackupFile()
{
#set -x
echo "Removing old backups if they exists." >> "${report}"
local RCLOC=0
spaceBefore=$(getAvailableSpace ${backupDirectory})
timesToWait=60 # Wait a maximum of 10 minutes before bailing
while read fileName
do
...
done < ${oldDbContainer}
return $RCLOC
}
Calculate duration in HH:MM:SS format using difference in start and end time.
# Time Arithmetic
TIME1="00:30:20"
TIME2="00:30:50"
# Convert the times to seconds from the Epoch
SEC1=`date -j -f '%T' $TIME1 "+%s"`
#echo $SEC1
SEC2=`date -j -f '%T' $TIME2 "+%s"`
#echo $SEC2
# Use expr to do the math, let's say TIME1 was the start and TIME2 was the finish
DIFFSEC=`expr ${SEC2} - ${SEC1}`
#echo $DIFFSEC
echo Start ${TIME1}
echo Finish ${TIME2}
echo Took ${DIFFSEC} seconds.
# And use date to convert the seconds back to something more meaningful
result=`date -r $DIFFSEC "+%T"`
echo Result ${result}
Expected : Result 00:30:30 00:00:30(corrected)
Actual : Result 05:30:30
EDIT Actual TIME1 and TIME2 will be coming as params, and intension here is not to calculate time elapsed. It is a sample code i have used to demonstrate the issue. Strangely when TIME1=05:30:20 and TIME2=05:30:50 then also Result is : 05:30:30
Corrected Subject.
I finally settled with below, thanks anyways.
result=$(printf '%02d:%02d:%02d' $(($DIFFSEC/3600)) $(($DIFFSEC%3600/60)) $(($DIFFSEC%60)))
I need help using time in the c-shell
I want to know how much time it took to execute a script,so i want to do in the following way
1.set start_time=time
2 script part
3.set end_time=time
4. set diff=end_time-start_time
5.echo "It took $diff seconds"
but i couldn't get the time value using any command.
could any one suggest a command to read the time value in c-shell
I think you want the "date" command, with the format to give you raw seconds:
# start_time = `date +%s`
script part
# end_time = `date +%s`
# diff = $end_time - $start_time
echo "It took $diff seconds"