1

It is a newbie question, please bear with me... I need to get every Tuesdays and Fridays by looping dates as follows:

enddate='2023-05-15'
startdate=2022-12-27
d1=
    while ! [[ $d1 > $enddate ]]; do  
    startdate=$(date -d "$startdate + 7 days" +%Y-%m-%d)
d1=$(date -d "$startdate +3 days" +%Y-%m-%d)
    result=$(printf "$startdate $d1")
echo ${result[@]} | tr "\n " " "
done 

This prints the values correctly. How can I get this result stored in an array? $ ./dates.sh 2023-01-03 2023-01-06 2023-01-10 2023-01-13 2023-01-17 2023-01-20 2023-01-24 2023-01-27 2023-01-31 2023-02-03 2023-02-07 2023-02-10 2023-02-14 2023-02-17 2023-02-21 2023-02-24 2023-02-28 2023-03-03 2023-03-07 2023-03-10 2023-03-14 2023-03-17 2023-03-21 2023-03-24 2023-03-28 2023-03-31 2023-04-04 2023-04-07 2023-04-11 2023-04-14 2023-04-18 2023-04-21 2023-04-25 2023-04-28 2023-05-02 2023-05-05 2023-05-09 2023-05-12 2023-05-16 2023-05-19

I tried this: result=$(echo ${result[@]} | tr "\n " " ") echo ${result[@]} But I am getting this result: 2023-01-03 2023-01-06 2023-01-10 2023-01-13 2023-01-17 2023-01-20 2023-01-24 2023-01-27 ...

If I echo $result and save it to a file, I can get it looping line by line successfully, but I want it from an array.

ncspeck
  • 13
  • 2
  • `result` is not an array. You need to write something like `result=( "$startdate $d1" )`. BTW, what is the point of running `printf` in your code? – user1934428 Apr 19 '23 at 07:37

1 Answers1

3

Simply declare result as an array (declare -a result=()) and add elements with result+=( "$startdate" "$d1" ). Print the final result with printf '%s\n' "${result[@]}". Demo:

$ startdate='2022-12-27'
$ enddate='2023-05-15'
$ d1=
$ declare -a result=()
$ while ! [[ $d1 > $enddate ]]; do
    startdate=$(date -d "$startdate +7 days" +%Y-%m-%d)
    d1=$(date -d "$startdate +3 days" +%Y-%m-%d)
    result+=( "$startdate" "$d1" )
done 
$ printf '%s\n' "${result[@]}"
2023-01-03
2023-01-06
...
2023-05-16
2023-05-19
Renaud Pacalet
  • 25,260
  • 3
  • 34
  • 51
  • Avoid using forks like `$(date ...)` in loops. See backgrounded `date` in [Convert date time string to epoch in Bash](https://stackoverflow.com/a/49195703/1765658) or simply do this [in integer](https://stackoverflow.com/a/76054060/1765658) – F. Hauri - Give Up GitHub Apr 19 '23 at 11:44
  • Why not. But the question was not about performance. I personally prefer direct answers with minimal changes. – Renaud Pacalet Apr 19 '23 at 15:15
  • Thanks to both, finally got it working. – ncspeck Apr 20 '23 at 03:20