Search code examples
bashloops

how to store/append multiple dates in Bash


How can I store values and concatenate them to one variable? all_dt (final variable) should take this into account that it is possible that output of both variables in A or output from B or both A, and B may not have any date values but

A) start_dt_inc and end_dt variables store two date values:

start_dt_incr=$(psql -q -A -t -c "select cast(coalesce(max(date_key),'1900-01-01')+ interval '1 day' as varchar (10)) from target table;" -d ${database_name})

 end_dt=$(psql -q -A -t -c "select process_dt from process_table;" -d ${database_name})

For this example, assume stored values are:

start_dt_incr='2024-05-02' 
end_dt='2024-05-03'

B) Can I store the output of this sql in variable "start_end_dt_hist" like below (please see attempt#1)?

 SELECT concat(cast(MIN(g.dt)::date as CHAR(10)), '|',cast(MAX(g.dt)::date as CHAR(10)))
FROM generate_series(date '2019-06-25', '2024-01-15', '1 day') g(dt)
GROUP BY EXTRACT(YEAR FROM g.dt)
ORDER BY MIN(g.dt)::date;

Result:
2019-06-25|2019-12-31
2020-01-01|2020-12-31
2021-01-01|2021-12-31
2022-01-01|2022-12-31
2023-01-01|2023-12-31
2024-01-01|2024-01-15 

Attemtp#1: store historical dates in variable:

start_end_dt_hist=$(psql -q -A -t -c "SELECT concat(cast(MIN(g.dt)::date as CHAR(10)), '|',cast(MAX(g.dt)::date as CHAR(10))) FROM generate_series(date '2019-06-25', '2024-01-15', '1 day') g(dt) GROUP BY EXTRACT(YEAR FROM g.dt) ORDER BY MIN(g.dt)::date;" -d ${database_name})

C) How can I concatenate values from A, and B (start_dt_incr, end_dt and start_end_dt_hist) as following, assuming variable to hold all of this will be called "all_dt".

all_dt=
2024-05-02|2024-05-03 
2019-06-25|2019-12-31
2020-01-01|2020-12-31
2021-01-01|2021-12-31
2022-01-01|2022-12-31
2023-01-01|2023-12-31
2024-01-01|2024-01-15

Solution

  • Not sure what exactly do you want. You can check the following examples, may be they help you to clarify your needs: 1)

      start_dt_incr='2024-05-02' 
      end_dt='2024-05-03'
      start_end_dt_his="$start_dt_incr $end_dt"
    
      start_end_dt_his="$(psql -q -A -t -c "select cast(coalesce(max(date_key),'1900-01-01')+ interval '1 day' as varchar (10)) from target table;" -d ${database_name}) $(psql -q -A -t -c "select process_dt from process_table;" -d ${database_name})"
    
    start_end_dt_his="start_end_dt_his
    $start_dt_incr $end_dt"