0

I'm trying to do something very simple that consists in insert a set of dates into an array. So I run a git command which wil return an one line result, from that result I'm getting the dates using awk. After I iterate over all dates and add them to the array. In the end, the array is still empty but if I print the array during the loop it seems to have data inside.

Why is the array empty after the loop?

git reflog --date=local <branch_name> | 
awk '{ print $3 " " $4 " " $5 }' | 
while read date; do a+=(`echo "$date"`); done; echo ${a[@]}

I understand that every command after a pipe is executed in a different subshell, but in this case I think it is not influencing the final result...

1
  • Since you are assigning a variable in a subshell, so the variable scope is the subshell and the parent can't see it. Commented Oct 16, 2014 at 16:24

1 Answer 1

4

Your while loop is running in a subshell, so the variable is out of scope after it finishes.

Since you are using bash you can use process substitution instead:

while read date; do 
    a+=( $(echo "$date") )
done < <(git reflog --date=local <branch_name> | awk '{ print $3 " " $4 " " $5 }')
echo "${a[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

Oh god, so my supposition was completely wrong. It works. Thanks!

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.