Wednesday, July 27, 2022

[SOLVED] Looping through hour value in Unix

Issue

I have date variable with format yyyymmddhh. I am trying to loop through the hour element in it. I tried below way but it's failing to produce output.

now=2018100600
end=2018100804
while [ "$now" != "$end" ] ;
do
        now=`date +"%Y%m%d%H" -d "$now + 1 hour"`;
        echo $now
done

Output expected from above script is 2018100601,2018100602,...2018100804

I am getting error as date: invalid date ‘-53382311010101 + 1 hour'.

What can I try next?


Solution

I think that it's the best to give GNU date only dates in format YYYY-mm-dd HH-MM-SS. He keeps on misinterpreting the input date format. In case you have an openbsd date version (which I like), you can specify the input string fields.

This works:

now=2018100600
end=2018100604
while (( now < end )); do
        now=$(
            date --date="${now:0:4}-${now:4:2}-${now:6:2} ${now:8:2}:00:00 +hour" +%Y%02m%02d%02H
        )
        echo "$now"
done

but I still feel like using timestamps is safer:

now_timestamp=$(date --date="${now:0:4}-${now:4:2}-${now:6:2} ${now:8:2}:00:00" +%s)
end_timestamp=$(date --date="${end:0:4}-${end:4:2}-${end:6:2} ${end:8:2}:00:00" +%s)
for ((i = now_timestamp; i < end_timestamp; i += 60 * 60)); do
    now=$(date --date="@$i" +%Y%02m%02d%02H)
    echo "$now"
done

Live example available at tutorialpoint.



Answered By - KamilCuk
Answer Checked By - Senaida (WPSolving Volunteer)