Operations with DATE in bash

3.6k Views Asked by At

So I need to create a script that writes in a file details about phone calls. The file needs to contain: -CALLING_NUMBER -> which starts with 0742, 0743 and 0744, the rest of the digits being randomly generated ( 10 in total )

-CALLED_NUMBER -> which starts with 07 and the rest of the digits also random

-START_DATE -> the start date of the phone call, in format yyyy-mm-dd hh24:mm:ss. For all phone calls, the start date needs to be from the same day and cover all the hours in that day

-END_DATE -> the end date of the phone call, in the same format, greater than the start date, randomly generating the extra seconds between 0-7200

-CALL_TYPE -> if the duration of the call is 1 sec, it return SMS, if it is longer, it returns VOICE

I did the CALLING_NUMBER and the CALLED_NUMBER and the CALL_TYPE is pretty straight forward once you have end and start date. I am having troubles with the start and end date.

GNU bash,version 3.2.25(1)-release (x86_64-redhat-linux-gnu)

Thanks!

1

There are 1 best solutions below

0
randomir On BEST ANSWER

This will generate a random start_date anchored on a specific day, and then a random end_date that is 0-7200 seconds later than that:

#!/bin/bash

# all start_date's will be on this day
start_date_anchor="2017-09-01"
# start_date in seconds since Unix epoch
start_date_zero=$(date -d "$start_date_anchor" +%s)
# random offset in seconds from midnight (note: RANDOM is a 15-bit int)
start_date_offset=$(( ((RANDOM<<15)|RANDOM) % 86400 ))
# random start_date in "YYYY-MM-DD HH:MM:SS" format
start_date=$(date -d @"$((start_date_zero + start_date_offset))" +"%F %T")

# 0-7200 seconds offset
end_date_offset=$((RANDOM % 7200))
# end_date in "YYYY-MM-DD HH:MM:SS" format
end_date=$(date -d @"$((start_date_zero + start_date_offset + end_date_offset))" +"%F %T")

echo "Start date: $start_date"
echo "End date: $end_date"

Note we use here:

  • date -d 'some_date' +%s to convert some_date to Unix timestamp (seconds since epoch)
  • bash RANDOM variable, which returns a random integer in a 15-bit range (0 to 32767) each time it is called/referenced. We can get a 30-bit random integer by combining bits of two 15-bit integers with: RANDOM<<15 | RANDOM.
  • date arithmetic in seconds
  • date -d @unix_timestamp to convert Unix timestamp back to human-readable date/time
  • +"%F %T" format specifier as a shortcut for the YYYY-mm-dd HH:MM:SS format