git - Bash 脚本协助查找

标签 git bash

我正在尝试编写一个由每日 cron 计划调用的 bash 脚本,该脚本将循环查找 .git 目录的所有子目录,在该存储库上运行 git pull --all 来更新存储库并获取任何新分支,跟踪这些分支,然后转到下一个存储库。我是 bash 脚本初学者,熟悉一些 Linux。我的问题是我在 How to clone all remote branches in Git? 找到的 for 循环但现在似乎无法正常运行,因为我已将其引入到我的脚本中,并且对 cd ${line}.. 的调用似乎没有按预期工作。我想知道我做错了什么以及如何解决它的一些指导。谢谢。

我当前的脚本gitcron.sh:

#!/bin/bash

find . -maxdepth 2 -name .git -type d -print > .gitrepos

while read -r line; do
  cd ${line}/..
  git pull --all
  for branch in $(git branch --all | grep '^\s*remotes' | egrep --invert-match '(:?HEAD|master)$'); do
     git branch --track "${branch##*/}" "$branch"
  done
done < ".gitrepos"

.gitrepos 生成的文件:

./codeigniter/.git
./magento/.git
./magento2/.git

我的问题:

gitcron.sh: line 6: cd: ./magento2/.git/..: No such file or directory
fatal: it does not make sense to create 'HEAD' manually
error: unknown switch `>'

最佳答案

问题是您已经使用 cd ${line}/.. 更改了工作目录(并且不断更改),即转到 {line} 的父目录>。一切都在同一个 shell session 中完成。第一次运行后,目录将更改为 line 变量第一个值的父目录,因此下一次运行(可能)会因为找不到父目录而失败(因此 .git 也不会出现)。

要解决此问题,您可以:

  • find中使用目录的绝对路径:

    find /foo/bar/ ...
    

    然后像现在一样使用while

  • 或者在子 shell 中运行 cd 和连续的 block :

    while ...; do (cd ...; ...); done <file
    

作为旁注,(始终)引用变量扩展以防止分词和路径名扩展。

关于git - Bash 脚本协助查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44993623/

相关文章:

git - 始终在 TortoiseGit 中添加提交作者和日期

Git - 从代码中删除之前的 'Saving' 调试语句

ruby - 如何构建包装器脚本

linux - 没有覆盖 -n 被 cp 命令忽略

linux - 使用 sudo 运行 shell 脚本时,用户路径不可用

GitHub for Windows 看不到存储库中的更改

git - Gig2go : unpacking the sent packfile failed on the remote

macos - OS X 上的 Bitbucket 权限被拒绝(公钥)Git

linux - 如何从 shell/bash 脚本中更改 linux 上的桌面墙纸

linux - Shell 脚本未启动服务