除了将推送 URL 更改为无效的内容(例如,git remote set-url --push origin DISABLED)外,还可以使用 pre-push 挂钩。
阻止git push 的一种快速方法是将/usr/bin/false 符号链接为钩子:
$ ln -s /usr/bin/false .git/hooks/pre-push
$ git push
error: failed to push some refs to '...'
如果需要,使用钩子可以对推送进行更细粒度的控制。请参阅.git/hooks/pre-push.sample,了解如何防止推送正在进行的提交的示例。
为了防止推送到特定分支或限制推送到单个分支,在示例钩子中这样做:
$ cat .git/hooks/pre-push
#!/usr/bin/sh
# An example hook script to limit pushing to a single remote.
#
# This hook is called with the following parameters:
#
# $1 -- Name of the remote to which the push is being done
# $2 -- URL to which the push is being done
#
# If this script exits with a non-zero status nothing will be pushed.
remote="$1"
url="$2"
[[ "$remote" == "origin" ]]
具有多个遥控器的测试存储库:
$ git remote -v
origin ../gitorigin (fetch)
origin ../gitorigin (push)
upstream ../gitupstream (fetch)
upstream ../gitupstream (push)
允许推送到origin:
$ git push origin
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Writing objects: 100% (3/3), 222 bytes | 222.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To ../gitorigin
* [new branch] master -> master
不允许推送到任何其他遥控器:
$ git push upstream
error: failed to push some refs to '../gitupstream'
请注意,pre-push 钩子脚本可以修改为向 stderr 打印一条消息,说明推送已被禁用。