2

I have the following problem in a Bash script:

On execution of the script a Zenity popup box opens to ask how many date entries should occur. If for example 3 is entered then a further 3 Zenity boxes are opened up (one after another) to ask for a date entry.

From this I am able to generate two variables ($tvar and $date_entry_number). $date_entry_number captures the amount of dates entered and $tvar captures all dates entered, separated by white-space. In the case of $date_entry_number = 3, $tvar might be = '2020-07-02' '2020-07-03' '2020-07-04'.

What I am trying to do is create variables containing individual dates from $tvar, such as $tvar1='2020-07-02' $tvar2='2020-07-03' $tvar3='2020-07-04' base on $date_entry_number which could be any number. This would mean that there could be any number of dates in $tvar.

My thinking is that I would need a for loop as you can see in the script below but I am not sure how to do this properly. Can someone please help?

#!/bin/bash

date_entry_number="$(zenity --entry --text "ENTER number of date_entries:" --entry-text "1")" a=1

tvar=$(until [[ $date_entry_number -lt $a ]] do

date_out="$(zenity --calendar
--title="Select a Date"
--text="Click on a date to select that date."
--date-format="'%G-%m-%d'")"

var="${date_out}"

echo $var

let a++

done)

echo $tvar echo $date_entry_number

for i in {1..$date_entry_number} do

    nvar{1..$tvar}

done

echo $nvar{1..$tvar}

Giacomo1968
  • 58,727

1 Answers1

3

It is possible to create variables like tvar1 but bash has arrays and that is an overall better approach. Here is how to create an array tvar that contains each date as an entry:

#!/bin/bash    
date_entry_number="$(zenity --entry --text "ENTER number of date_entries:" --entry-text "1")"

tvar=() a=1 until [[ $date_entry_number -lt $a ]] do tvar+=("$(zenity --calendar
--title="Select a Date"
--text="Click on a date to select that date."
--date-format="'%G-%m-%d'")") let a++ done

Show what's in the array

declare -p tvar

Loop through the indices of the array

for i in "${!tvar[@]}" do echo "date $i = ${tvar[i]}" done

In the above tvar=() creates an array called tvar.

tvar+=(...) appends what is in the parens to the end of array tvar. We use this to append each new date as it is entered.

Bash expands ${!tvar[@]} to become a list of the array indices. If i is an index in the array, as in the code above, we can access the corresponding value with ${tvar[i]} It we wanted a list of the array values, we would use ${tvar[@]}

For more information on the many powerful features of bash arrays, see the section in man bash entitled Arrays.

John1024
  • 17,343