所以我有两台笔记本电脑共享一个github repo(和同一个分支)。一台笔记本电脑上的一个自动程序正在修改robot.txt
,而我正在手动修改另一台笔记本电脑上的math.html
。
问题是,假设两台笔记本电脑都有正确的时间,我如何在自动bash脚本中使用git实现cp -u
的效果?注意,git merge --allow-unrelated-histories
不是理想的,因为我经常遇到手动输入git命令来解决(不存在的)冲突的情况。
你可以:
<- 拉变化/gh>
- 添加更改
- 提交这些更改 <
- 推动变化/gh>
:
git pull --rebase --autostash &&
git add -A &&
git commit -m "autosync: $(date -R)" &&
git push
如何以编程方式确定是否有未提交的更改?如果有任何变化,您可以添加一个检查。
类似下面的操作应该可以工作(除非两台笔记本电脑正在修改同一个文件,这会导致推送竞争)。如果你发现任何错误或改进,请告诉我。
if git fetch origin master -q 2>/dev/null
then
# first add (but do not commit) to compare with origin/master
git add . -A --ignore-errors
while read -r file
do
remote_time=`git log origin/master -1 --pretty="format:%at" -- "$file" 2>/dev/null`
local_time=`git log -1 --pretty="format:%at" -- "$file" 2>/dev/null`
# If remote time is not empty and local time
# is either empty (new file from remote) or
# has a smaller value (updated file from remote)
if [[ $remote_time != '' && ($local_time == '' || $remote_time > $local_time) ]]
then
git checkout origin/master --no-overlay -- "$file" 2>/dev/null
fi
done < <(git diff --name-only origin/master 2>/dev/null)
# (imagine without the following reset, the HEAD
# and working tree now also differs at those files
# we obtained from remote just now and therefore
# they get committed again.) reset ensures commit
# only contains file that we want to update from
# our side
git reset --soft origin/master
git add . -A --ignore-errors &&
git commit -m "sync.sh" -q >/dev/null &&
git push -f origin master -q
fi