Episode #125 of the Stack Overflow podcast is here. We talk Tilde Club and mechanical keyboards. Listen now
2 of 3 added 20 characters in body

echo $variable > file in a loop outputs only the last value of variable

Here's what I'm trying to do:
I have several git repos. I want to setup a push-to-deploy script for each of them. being so lazy to do that for each and every repo, I wanted to script it.

My script generates a post-receive file for each repo.

#!/bin/bash

REPOS=/var/opt/gitlab/git-data/repositories/user

for i in $(ls $REPOS)
do
        DEPLOY_DIR=/home/user/public_html/"$i"/
        POST_RECEIVE_DIR=$REPOS/"$i".git/hooks/post-receive

        echo -e '
from, to, branch = ARGF.read.split " "\r
\r
 # 3. Copy files to deploy directory\r
deploy_to_dir = File.expand_path('$DEPLOY_DIR')\r
`GIT_WORK_TREE="#{deploy_to_dir}" git checkout -f master`\r
puts "DEPLOY: master(#{to}) copied to '#{deploy_to_dir}'"\r
' > $POST_RECEIVE_DIR
        chmod +x $POST_RECEIVE_DIR

done

Notice that the only part that changes in the generated file is where $DEPLOY_DIR lies.
And $DEPLOY_DIR changes with each iteration.
The problem is: ALL the generated files have the LAST value of $DEPLOY_DIR.

To debug I tried to echo the variable values in various places in the script and they all produce the desired outputs. I thought it could be a problem with the buffers not being flushed. so I tried to use the sync command. I tried using cat instead of echo. I tried to pass the file as a parameter to a python script where I write to the file and flush the buffer.

All failed to work.