无法将以空格分隔的文件添加到git
我一直在编写一个脚本来使用 git add 添加未跟踪的文件。 我在脚本中使用的循环是
for FILE in $(git ls-files -o --exclude-standard); do
git add $FILE
git commit -m "Added $FILE"
git push origin master
done
脚本运行良好,直到它遇到一个包含空格的文件名。例如,我无法添加文件 Hello 22.mp4
。(请注意,Hello 和 22 之间有一个 SPACE)。上面的循环会将文件视为 2 个单独的文件:Hello 和 22.mp4,然后错误退出。 有人知道如何将其添加为单个文件吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
发生的情况是 shell 将
$(...)
扩展为一堆单词,并且它显然将嵌入空格的文件解释为多个文件。 即使之前建议引用git add
命令,它也不起作用。因此,循环使用错误的参数运行,如set -x
的输出所示:正确的解决方案是引用
git add $file
and< /em> 使用git ls-files
NULL 通过将-z
传递给git ls-files
来分隔文件名,并使用带有 null 的 while 循环分隔符: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 thegit add
command, it wouldn't work. So the loop is getting run with wrong arguments, as shown by this output withset -x
:The proper solution is to quote the
git add $file
and havegit ls-files
NULL separate the filenames by passing-z
togit ls-files
and use a while loop with a null delimiter:如果您使用 bash 替代 @AndrewF 提供的解决方案,则可以使用 IFS bash 内部变量将分隔符从空格更改为换行符,这些行中的内容:
这仅供您参考。 AndrewF 的响应提供了更多信息,涵盖调试选项和使用 while 代替 for。
希望这有帮助!
If you are using bash alternative to the solution provided by @AndrewF, you can make use of IFS bash internal variable to change the delimiter from space to newline, something on these lines:
This is just for your information. The response of AndrewF is more informative covering debugging option & usage of while instead of for.
Hope this helps!
尝试将
$FILE
var 放在引号中:这将引用文件名,从而允许其中包含空格。
Try putting the
$FILE
var in quotes:That'll quote the filename, thus allowing spaces in it.
将
git add $FILE
替换为git add "$FILE"
。这样它将被解释为单个元素。Replace
git add $FILE
withgit add "$FILE"
. That way it will be interpreted as a single element.我知道这已经很晚了,但这是使用标准 xargs linux 命令的一种方法:
您可以通过简单地回显命令来测试它,如下所示:
I know that this is very late but here is one way to do it using the standard xargs linux command:
You can test it by simply echoing the command as follows:
要添加为单个文件,请在文件名中的空格前添加反斜杠:
git add pathtofilename/filenamewith\ space.txt
To add as a single file add a backslash before the space in the filename:
git add pathtofilename/filenamewith\ space.txt