harithahv harithahv - 3 months ago 7
Git Question

Can't add a file separated with space to git

I have been writing a script to add untracked files using git add .
The loop I use in my script is

for FILE in $(git ls-files -o --exclude-standard); do
git add $FILE
git commit -m "Added $FILE"
git push origin master
done


The script runs fine till it faces a filename which has space in it. for Eg., I cant add the file
Hello 22.mp4
.(Note that there is a SPACE between Hello and 22). The above loop would take the file as 2 separate files, Hello and 22.mp4 and exit with error.
Does someone know how to add it as a single file?

Thanks

Answer

What's happening is the shell is expanding the $(...) into a bunch of words, and it's obviously interpreting a file with spaces embedded as multiple files obviously. Even with the prior suggestions of quoting the git add command, it wouldn't work. So the loop is getting run with wrong arguments, as shown by this output with set -x:

ubuntu@up:~/test$ ls -1
a a
ubuntu@up:~/test$ set -x; for FILE in $(git ls-files -o --exclude-standard); do git add "$FILE"; git commit -m "Added $FILE"; done
+ set -x
++ git ls-files -o --exclude-standard
+ for FILE in '$(git ls-files -o --exclude-standard)'
+ git add a
...

The proper solution is to quote the git add $file and have git ls-files NULL separate the filenames by passing -z to git ls-files and use a while loop with a null delimiter:

git ls-files -o --exclude-standard -z | while read -r -d '' file; do
  git add "$file"
  git commit -m "Added $file"
  git push origin master
done
Comments