Unable to add space separated file on git

I am writing a script to add files without a trace using git add. The loop that I use in the 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 works fine until a file name appears with a space in it. for eg., I cannot add the Hello 22.mp4 file. (Note that there is SPACE between Hello and 22. The above loop will take the file as two separate files, Hello and 22.mp4, and will fail. Does anyone know how to add it as a single file?
Thanks

+4
source share
6 answers

What happens, the shell extends $(...) by a bunch of words and, obviously, interprets the file with spaces embedded as several files. Even with previous suggestions for quoting the git add command, it does not work . Thus, the loop starts with incorrect arguments, as shown in this output using set -x :

 ubuntu@up :~/test$ ls -1 aa 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 correct solution is to tell git add $file and git ls-files NULL to separate the file names by passing -z to git ls-files and use a while loop with a zero separator:

 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 
+9
source

If you are using bash as an alternative to the solution provided by @AndrewF, you can use the IFS bash internal variable to change the separator from space to a new line, something in these lines:

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

This is for your information only. AndrewF's answer is more informative, covering the debugging option and using while, rather than for.
Hope this helps!

+4
source

Try typing $FILE var in quotation marks:

 git add "$FILE" 

This will indicate the name of the file, thus allowing spaces in it.

+2
source

Replace git add $FILE with git add "$FILE" . Thus, it will be interpreted as one element.

+1
source

I know this is very late, but here is one way to do this using the standard xargs linux command:

 git ls-files -o --exclude-standard | xargs -L 1 -I{} -d '\n' git add '{}' 

You can verify this by simply repeating the command as follows:

 git ls-files -o --exclude-standard | xargs -L 1 -I{} -d '\n' echo "git add '{}'" 
0
source

To add a backslash before a space in a file name as a separate file:

git add pathtofilename / filenamewith \ space.txt

0
source

Source: https://habr.com/ru/post/1388879/


All Articles