0

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

1 Answers1

2

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
ponteshare
  • 36
  • 1