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.

    for i in $(ls $REPOS)
            echo -e '
    from, to, branch = " "\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
            chmod +x $POST_RECEIVE_DIR


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.