Thursday, September 23, 2010

bash: Iterate through items containing spaces

I had branched from origin/MIS-58, and wanted to iterate through a list of all files that were either new or had changed since then. However, some filenames have spaces in them.

You can see the problem here, where the file 'DeploymentInstructions/MIS-187 Deployment Instructions.txt' is split over three lines by the for loop:
$ for i in $(git diff --name-only origin/MIS-58 HEAD) ; \
do echo $i ; done
DeploymentInstructions/MIS-187
Deployment
Instructions.txt
DeploymentInstructions/Unanet_i2_deployment_instructions.txt
HR/InstallScripts/JOB_FUNCTION_FLEX.ldt
HR/InstallScripts/LOAD_DEFAULT_JOB_FUNCTIONS.sql
HR/data/job_functions.csv
...


'-z' to the rescue:
$ git diff -z --name-only origin/MIS-58 HEAD | \
while read -d $'\0' file ; do echo $file ; done
DeploymentInstructions/MIS-187 Deployment Instructions.txt
DeploymentInstructions/Unanet_i2_deployment_instructions.txt
HR/InstallScripts/JOB_FUNCTION_FLEX.ldt
HR/InstallScripts/LOAD_DEFAULT_JOB_FUNCTIONS.sql
HR/data/job_functions.csv
...