1
Today=$(date)
for i in {2..15}
do
 week_{$i}=$(date -d "$Today +$i week")
 echo ${week_2}
done

I am getting no values in output in BASH.

5
  • One error easily spotted is "Today=$date" which assigns the value of the variable "date" to the variable named "Today". Try Today=$(date);echo $Today for a start. Commented Feb 7, 2016 at 17:40
  • I faintly remember that a for-loop opens a sub-shell, and any variable is local to that sub-shell and no way to set those values in the parent shell. Commented Feb 7, 2016 at 18:13
  • no-way except to place the values in a file (or a pipe??) and extract them afterwards. Commented Feb 7, 2016 at 18:14
  • 1
    @Starkeen it looks like there is a typo in your edit. Putting "Today=$date for i in {2..15} do" in one line gives a syntax error. Should be 2 lines or a ";" befor the "for". Commented Feb 7, 2016 at 18:37
  • and another newline or semicolon before the "do" Commented Feb 7, 2016 at 18:46

1 Answer 1

1

One way...

    Today=$(date)
    for i in {2..15} 
    do
        tmp=$(date -d "$Today +$i week")
        eval week_${i}=\$tmp
        eval echo  \$week_${i}
    done
    

Second way...

    Today=$(date)
    for i in {2..15} 
    do
        week_[$i]=$(date -d "$Today +$i week")
        echo ${week_[$i]}
    done
Third way...

    Today=$(date)
    for i in {2..15} 
    do
        eval echo \${week_${i}:=$(date -d "$Today +$i week")} > /dev/null
    done

    for i in {2..15} 
    do
        eval echo  \$week_${i}
    done
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain a bit? I'm no rookie to bash, but I mostly just used it. Transferring variable assignments from within a loop to the outside, I could never manage, and I had some try about it. It was a while loop, but I can' believe "for" could be much different.
In this examples variables available after loop. See second loop in "Third way".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.