Score:0

Bash loop through dates

sz flag

I'm trying to copy data from psql via a bash script now I'm stuck with a loop my bash script is as following:

#!/bin/bash
DATEBEGIN=2016-03-01
DATEEND=2016-03-31
DATEMONTH=2016-03

echo "Copy data to /mnt/bigstorage/samples-$DATEMONTH.csv file, please wait..."

psql postgresql://XXX:XXX@localhost/XXX << EOF
       COPY (SELECT  *
FROM    sample
WHERE   timestamp >= '$DATEBEGIN' AND
        timestamp <= '$DATEEND') TO '/mnt/bigstorage/backup/samples$DATEMONTH.csv' DELIMITER ',' CSV;
EOF

With the script above i need to change the months everytime because we need to copy the data till 2022 how can i loop trough dates? for example per month but per day is also fine.

Via the following script i get a list of days but i don't know how to implement this is my script

start=2016-01-01
end=2022-01-01
while ! [[ $start > $end ]]; do
    echo $start
    start=$(date -d "$start + 1 day" +%F)
done
Score:2
cd flag

don't know if I understood the question right but you could do something like that:

#!/bin/bash

start=2016-01-01
end=2022-01-01

while ! [[ $start > $end ]]; do

DATEBEGIN="$start"
start=$(date -d "$DATEBEGIN + 1 Month" +%F)
DATEEND=$(date -d "$start - 1 Day" +%F)
DATEMONTH=$(date -d "$DATEBEGIN" +%Y-%m)

echo "Copy data to /mnt/bigstorage/samples-$DATEMONTH.csv file, please wait..."

psql postgresql://XXX:XXX@localhost/XXX << EOF
COPY (SELECT  *
FROM    sample
WHERE   timestamp >= '$DATEBEGIN' AND
        timestamp <= '$DATEEND') TO '/mnt/bigstorage/backup/samples$DATEMONTH.csv' DELIMITER ',' CSV;
EOF

done
Sander Böhm avatar
sz flag
Yes that's it! thank you very much.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.