加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 无法添加用空格分隔的文件到git

发布时间:2020-12-14 01:36:36 所属栏目:Linux 来源:网络整理
导读:我一直在编写一个脚本来使用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 脚本运行正常,直到它面对一个文件名,里
我一直在编写一个脚本来使用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之间存在空格).上面的循环将文件作为2个单独的文件,Hello和22.mp4并退出并出错.
有人知道如何将其添加为单个文件吗?
谢谢

解决方法

发生了什么事情是shell正在将$(…)扩展为一堆单词,显然它解释了一个空间嵌入多个文件的文件.即使有引用git add命令的先前建议,它也行不通.所以循环使用错误的参数运行,如使用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
...

正确的解决方案是引用git add $file并将git ls-files NULL分隔文件名,方法是将-z传递给git ls-files并使用带有空分隔符的while循环:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读