从脚本执行 git 提交

Executing git commits from script

我想将一些文件从脚本提交到我拥有的 git 服务器,这需要自动完成。

我的脚本(驻留在 ~/bin 中)执行类似这样的操作

rsync -arE --delete --files-from=~/files.list / ~/repo
git --git-dir ~/repo/.git add ~/repo/*
git --git-dir ~/repo/.git commit -m "automatic commit #123"
git --git-dir ~/repo/.git push

我希望它将文件 ~/files.list 中列出的文件复制到 ~/repo(rsync 处理这个),然后将这些文件添加到存储库,提交并推送。

但是,它无法正确地将文件添加到 git 提交,特别是它总是抓取工作目录中的文件(在本例中为 ~/bin),所以我需要一种方法:

  1. git 命令更改 运行 目录
  2. 告诉git从工作目录以外的目录添加文件

听起来你想要的是 Git 的 -C 选项,它在 运行 之前更改当前目录。你可以这样写:

rsync -arE --delete --files-from=~/files.list / ~/repo
git -C ~/repo/ add .
git -C ~/repo/ commit -m "automatic commit #123"
git -C ~/repo/ push

当然,你也可以把它写成一个cd和一个subshel​​l,但是上面的可能更简单一些:

rsync -arE --delete --files-from=~/files.list / ~/repo
(cd ~/repo/ &&
 git add .
 git commit -m "automatic commit #123"
 git push)

我假设您的 rsync 命令已经按照您的意愿执行。

无需复制,只需告诉git您的工作文件在哪里。

git -C ~/repo --work-tree="$PWD" add .
git -C ~/repo commit -m etc
git -C ~/repo push

将您的 files.list 列表放入 .gitignore 格式,忽略除您希望 git 搜索的文件以外的所有内容,并将其作为回购的 .git/info/exclude :

# To include only this, and/this, and/that but ignore everything else:
# ignore everything
*
# except
!this
!and/this
!and/that
!etc
# do search inside directories, don't let ignores stop later searches inside
!*/

注意,命令行上的路径是相对于工作树的,如果你还没有在里面的话,所以如果你在一个仓库中并且想从其他地方添加内容,你可以 git --work-tree=/path/to/elsewhere add . 它会全部添加。