Что такое git push и как его использовать
В инструкции рассказываем о наиболее частых сценариях использования git push.
Эта инструкция — часть курса «Введение в Git».
Смотреть весь курс
Введение
Команда Git push позволяет отправлять локальную ветку на удаленный репозиторий. Она помогает разработчикам синхронизироваться в команде, а именно отправляет проделанные изменения. Если программист работает один, то пуш позволяет хранить код в облаке, например github, gitlab и не только, избавляя от риска потери данных на компьютере.
Дополнительно для синхронизации еще используют git pull для получения изменений с сервера и git remote, чтобы получить список удаленных подключений к репозиторию.
В этой инструкции мы расскажем, как запушить в удаленный git репозиторий. В статье под «пушем» будем подразумевать git push.
Отправка изменений в чистый репозиторий
Перед пушем надо связать локальный и удаленный репозитории. Делается это при помощи команды:
git remote add link
Вместо repository_name нужно дать имя удаленному репозиторию. Далее в инструкции вместо этого параметра мы будем использовать origin, так как чаще всего используют это имя.
Вместо link — ссылка на удаленный репозиторий, она может выглядеть по-разному в зависимости от того используется ssh или https.
Для ssh, который обязателен для github и gitlab, потребуются сделать дополнительные манипуляции для создания ssh-ключа. Соответствующие инструкции есть на этих ресурсах.
Отправка изменений
Перед пушем надо зафиксировать текущие изменения, то есть сделать git commit.
Далее для отправки в терминале пишем:
git push origin
Вместо branch — имя ветки, которую надо отправить. Чаще всего используется master или main:
git push origin master
Такое каждый раз писать слишком громоздко, для этого придумали git push по умолчанию. Для этого единожды набираем предыдущую команду с флагом -u:
git push -u origin master
После этого можно писать более коротко, так как git запомнил, что пушить надо на сервер origin ветку под именем master:
git push
Таким образом, git позволяет запушить ветку в удаленный репозиторий. Чтобы через git добавить ветку в удаленный репозиторий, надо запушить существующую локальную ветку.
Дополнительные опции публикации
Отправка ветки на сервер в ветку с другим именем
Для того чтобы сделать git push в другую ветку, есть специальный синтаксис, где после имени ветки через двоеточие пишется имя удаленной ветки:
git push origin branch:server_branch
где branch – имя локальной ветки, server_branch – имя удаленной ветки на сервере.
Отправка всех веток на сервер
Вместо имени ветки пишем флаг —all:
git push origin --all
После этого все зафиксированные изменения в ветках отправятся в удаленный репозиторий.
Отправка текущей ветки
Удобный способ отправить текущую ветку с тем же именем на сервере.
git push origin HEAD
HEAD указывает на текущую ветку (current branch). Тем самым, не надо запоминать имя ветки, на которой вы находитесь.
Принудительная публикация (git push —force …)
При отправке может произойти ошибка публикации:
To github.com:example/test.git ! [rejected] master -> master (fetch first) error: не удалось отправить некоторые ссылки в «github.com:example/test.git»
Это так называемый git push rejected, он означает что пуш был отклонен. Правильнее всего — сделать то, что написано в подсказке к ошибке. Надо получить и смержить изменения, затем снова отправить.
Эта ошибка происходит, так как git проверяет, что новый коммит основан на предыдущих коммитах. Пока вы вносили изменения, кто-то мог запушить изменения того же, над чем вы работали. Поэтому git не может выполнить автоматическое слияние, ваш коммит был раньше и он не базируется на обновленных коммитах в удаленном репозиториие.
Флагом —force или сокращенной его версией -f отключается проверка коммитов и при необходимости выполняется перезапись истории.
git push --force
Нужно быть аккуратными с этой командой, так как она стирает работу других людей. Эта команда оправдана лишь изредка, например, если вы почти сразу внесли изменения коммита с помощью git commit —amend и запушили до того, как кто-то сделал git pull.
Принудительная публикация с параметром (git push —force-with-lease …)
Это более безопасный, но так же нерекомендуемый вариант вариант принудительного пушинга. Он не перезапишет работу в удаленной ветке, если в нее были добавлены коммиты от других людей.
git push --force-with-lease
Принудительная публикация с этим параметром чревата появлением git push rejected у других людей
Как пушить в PhpStorm
При первом открытии PhpStorm потребуется создать новый проект.
В открытом проекте в правом верхнем углу среды разработки располагаются наиболее часто используемые команды git, в том числе пушинга.
Синяя стрелка означает git pull, зеленая галочка — git commit, зеленая стрелка — git push. При нажатии на зеленую стрелку (горячие клавиши Ctrl+Alt+K или ⌥ ⌘ K) открывается диалоговое окно с информацией об изменениях и настроках отправки.
Незапушенные коммиты
Самый простой способ узнать про них при помощи команды:
git status
Вывод будет содержать имя текущей ветки и то, насколько она опережает версию сервера. Пример вывода:
On branch master Your branch is ahead of ‘origin/master’ by 1 commit. (use “git push” to publish your local commits)
Для более подробной информации можно использовать:
git log
Будет выведена история коммитов:
commit 0fcd9558b013f642a8c3b4a59a16a66de39c99bd (HEAD -> master) Author: Pavel Date: Sun Mar 27 18:57:14 2022 +0300 Local commit commit 289c650767d2c7c2e58486e27b8b3933c6442078 (origin/master, origin/HEAD) Author: Pavel Date: Fri Mar 25 19:41:47 2022 +0300 Pushed commit
В скобках пишется где и какой коммит расположен.
HEAD -> master означает что текущая ветка (current branch) — это master и это последний локальный коммит в ней.
В нижнем коммите в скобках origin/master означает, что это последний опубликованный коммит на сервере в ветке master, а origin/HEAD, что коммит расположен на ветке, которая совпадает с локальной веткой HEAD.
Как пушить теги
Для создания тегов используют git tag, а для их отправки:
git push origin
Вместо tag_name — имя тега, который надо удалить на сервере.
Также можно сделать отправку всех тегов:
git push --tags
Мы не рекомендуем выбирать этот способ, так как могут отправиться теги, которые были удалены на сервере.
Удаление ветки или тега на сервере
Чтобы удалить ветку на удаленном репозитории, используем уже привычную команду с флагом —delete:
git push --delete origin
remote_branch_or_tag_name — имя ветки или тега на сервере.
Для удаление локальной ветки:
git branch -d
А для удаления локального тега:
How to force push to Gitlab
You can’t force push because «You are not allowed to force push code to a protected branch on this project». push —force is how you force push to GitLab, or anywhere else, as long as you’re allowed to.
Jan 8, 2019 at 22:25
Maybe their documentation will help: docs.gitlab.com/ee/user/project/protected_branches.html
Jan 8, 2019 at 22:25
Possible duplicate of Cannot push after BFG Repo-Cleaner
Jan 8, 2019 at 22:54
Jan 8, 2019 at 22:54
3 Answers 3
- Navigate to your project’s Settings ➔ Repository
- Scroll to find the Protected branches section.
- From the Branch dropdown menu, select the branch you want to protect and click Protect.
Following the steps above, you should be greeted with a box similar to this one below.

There, you can click either:
- «Allowed to force push» toggle button, or
- the orange Unprotect button
for the branch you want to force push to, e.g., master .
If you don’t want to navigate through the navigation bars, you can also fill out this URL template:
https://gitlab.com///settings/repository#js-protected-branches-settings
and replace and with your specific username and project name, respectively.
Note, the «Allowed to force push» button is probably favored over un-selecting the Unprotect button because branch protection gives you additional safety from accidentally deleting your branch. But either option appears to work.
- Community discussion on force pushing on branch https://gitlab.com/gitlab-com/support-forum/issues/93
- Official documentation to do so https://docs.gitlab.com/ee/user/project/protected_branches.html
Allow to force push option for protected branches
While preventing force push is generally best practice, there are certain exceptions that currently cannot be configured. Currently, maintainers can remove branch protections to allow temporary force push , however, all settings for the previously protected branch in question are lost. Finally, users migrating from competing services who made use of this feature have a break in their workflow. Notable use cases for this feature:
- Production incidents that require pushing an immediate fix, bypassing previously configured rules
- POC projects where an owner would want to always be able to force push to master
- Prevent force push for most branches except those matching a pattern, ie wip-*
More use cases on the #use cases section.
We should provide a more convenient way to allow force pushes for specific users/groups on protected branches.
Proposal
Add a new Allow force push toggle on the protected branches section, which will enable force push for any roles/groups/users defined in the Allow to push section.

Proposed tooltip text: Allows force push for users with push access.
Important note regarding Protected branches API: When protecting a branch via API and setting the unprotect_access_level to admin (60), only admins should be able to change the new Allow force push setting (like all other branch protection settings).
- Step 1, define which roles/groups/users are allowed to push

- Step 2, once roles/groups/users have been defined as allowed to push, «allow force push» option shows next to each item on the list

Previous proposal 1
Add a new setting on protected branches called ‘Allowed to Force Push’ which would enable maintaners/owners to define which user/groups have this elevated privilege.

- Add field Allowed to force push to the Protect a branch form
- Add field Allowed to force push to the list of protected branches
- Fields should behave as follows:
- Field should be defaulted to No one
- Clicking the field should open a dropdown selection
- Dropdown should allow the user to select one or more roles (or No one)
- Dropdown should allow the user to select one or more groups
- Dropdown should allow the user to select one or more users
- Dropdown should allow the user to search users
- Selecting an option should mark the option as selected and update input field
- Clicking an already selected option should unselect it
- Selecting No one should remove other role selections
- If No one is selected, clicking should not remove selection
- If a single role is displayed, display the role
- If more than 1 role is selected display N roles
- If one or more groups are selected, display N groups
- If one or more users are selected, display N users
- If a combination of roles, groups, and/or user are selected display N users, N groups, N roles
Customers:
- https://gitlab.my.salesforce.com/00161000006g0e6
- https://gitlab.my.salesforce.com/0016100001F4xr9
- https://gitlab.my.salesforce.com/00161000002xBfL
- https://gitlab.my.salesforce.com/0016100000fdsC1
- https://gitlab.my.salesforce.com/0016100001C37c6
- https://gitlab.my.salesforce.com/0016100001QRxpH
- https://gitlab.my.salesforce.com/00161000004bZPD
- https://gitlab.my.salesforce.com/0014M00001gSoye
- https://gitlab.my.salesforce.com/0016100001Eo6KV
- https://gitlab.my.salesforce.com/0016100001crSyM
- https://gitlab.my.salesforce.com/0016100001fOgW0
- https://gitlab.my.salesforce.com/00161000002xBaT
Links
This was originally proposed in gitlab-ce#20550
Use cases
- Doing a revert of code on the master branch and the getting develop branch back in sync with master, this is currently done via a force push. Ideally this would be done by automation when the scenario happens and a service account would have this access.
- Small teams (ie agencies) where owners want to quickly resolve conflicts themselves and they are the only maintainers on the project.
- Situations where a mistake (ie wrong git command) wreaked havoc and cost the teams hours to resolve. During postmortem agreed that force push should have been used to recover and analysis taken place later. Maintaner was not available until after the incident was resolved and the time was lost.
- Multiple branches must be synched with master. A lot of these are experimental and have a dedicated owner, currently, owners must unprotected, force push to sync with master, and then re-protect. The setting here would save time.
- Training using GitLab pages. Students use a pre-created branch, experiment with changes. When the next class is ready, I’d like to sync other branches with master by force pushing.
- Corrupted git repo. There is a missing tree, which can be fixed by force push to the previous commit and trying again. There are other ways to fix this, but this is the fastest an when pressed for time is a good option to consider. Especially helpful when maintainer is not availble to change repo settings but dev leads with «developer» role could do this.
- Use of protected master to deploy to production, and we want some members to be able to force push master to point to the head of the staging branch
- Org where all branches are protected but all WIP branches (using pattern on branch name WIP-* ) allow force push.
Управление правилом защиты ветвей
Вы можете создать правило защиты ветвей, чтобы принудительно применять определенные рабочие процессы для одной или нескольких ветвей, например, запрашивать проверку с целью утверждения или передавать проверки состояния для всех запросов на вытягивание, объединенных в защищенную ветвь.
Кто может использовать эту функцию.
People with admin permissions or a custom role with the «edit repository rules» permission to a repository can manage branch protection rules.
Protected branches are available in public repositories with GitHub Free and GitHub Free for organizations, and in public and private repositories with GitHub Pro, GitHub Team, GitHub Enterprise Cloud, and GitHub Enterprise Server. For more information, see «GitHub’s plans.»
About branch protection rules
You can create a branch protection rule in a repository for a specific branch, all branches, or any branch that matches a name pattern you specify with fnmatch syntax. For example, to protect any branches containing the word release , you can create a branch rule for *release* .
You can create a rule for all current and future branches in your repository with the wildcard syntax * . Because GitHub uses the File::FNM_PATHNAME flag for the File.fnmatch syntax, the * wildcard does not match directory separators ( / ). For example, qa/* will match all branches beginning with qa/ and containing a single slash, but will not match qa/foo/bar . You can include any number of slashes after qa with qa/**/* , which would match, for example, qa/foo/bar/foobar/hello-world . You can also extend the qa string with qa**/**/* to make the rule more inclusive.
For more information about syntax options, see the fnmatch documentation.
Note: Not all expressions from the fnmatch syntax are supported in branch protection rules. Please be aware of the following constraints:
- You cannot use the backslash ( \ ) character as a quoting character, as GitHub does not support the use of backslashes in branch protection rules.
- You can specify character sets within square brackets ( [] ), but you cannot currently complement a set with the ^ operator (e.g., [^charset] ).
- Although GitHub supports File::FNM_PATHNAME in fnmatch syntax, File::FNM_EXTGLOB is not supported.
If a repository has multiple protected branch rules that affect the same branches, the rules that include a specific branch name have the highest priority. If there is more than one protected branch rule that references the same specific branch name, then the branch rule created first will have higher priority.
Protected branch rules that mention a special character, such as * , ? , or ] , are applied in the order they were created, so older rules with these characters have a higher priority.
To create an exception to an existing branch rule, you can create a new branch protection rule that is higher priority, such as a branch rule for a specific branch name.
For more information about each of the available branch protection settings, see «About protected branches.»
Note: Only a single branch protection rule can apply at a time, which means it can be difficult to know how which rule will apply when multiple versions of a rule target the same branch. For information about an alternative to branch protection rules, see «About rulesets.»
Creating a branch protection rule
When you create a branch rule, the branch you specify doesn’t have to exist yet in the repository.
Note: Actors may only be added to bypass lists when the repository belongs to an organization.
- On GitHub.com, navigate to the main page of the repository.
- Under your repository name, click
Settings. If you cannot see the «Settings» tab, select the

dropdown menu, then click Settings.
Note: If you select Dismiss stale pull request approvals when new commits are pushed and/or Require approval of the most recent reviewable push, manually creating the merge commit for a pull request and pushing it directly to a protected branch will fail, unless the contents of the merge exactly match the merge generated by GitHub for the pull request. In addition, with these settings, approving reviews will be dismissed as stale if the merge base introduces new changes after the review was submitted. The merge base is the commit that is the last common ancestor between the topic branch and the base branch. If the merge base changes, the pull request cannot be merged until someone approves the work again.
- Under «Protect matching branches», select Require a pull request before merging.
- Optionally, to require approvals before a pull request can be merged, select Require approvals. Select the Required number of approvals before merging dropdown menu, then click the number of approving reviews you would like to require on the branch.
- Optionally, to dismiss a pull request approval review when a code-modifying commit is pushed to the branch, select Dismiss stale pull request approvals when new commits are pushed.
- Optionally, to require review from a code owner when the pull request affects code that has a designated owner, select Require review from Code Owners. For more information, see «About code owners.»
- Optionally, to allow specific actors to push code to the branch without creating pull requests when they’re required, select Allow specified actors to bypass required pull requests. Then, search for and select the actors who should be allowed to skip creating a pull request.
- Optionally, if the repository is part of an organization, select Restrict who can dismiss pull request reviews. Then, in the search field, search for and select the actors who are allowed to dismiss pull request reviews. For more information, see «Dismissing a pull request review.»
- Optionally, to require someone other than the last person to push to a branch to approve a pull request prior to merging, select Require approval of the most recent reviewable push. For more information, see «About protected branches.»
- Select Require status checks to pass before merging.
- Optionally, to ensure that pull requests are tested with the latest code on the protected branch, select Require branches to be up to date before merging.
- In the search field, search for status checks, selecting the checks you want to require.
- Select Lock branch.
- Optionally, to allow fork syncing, select Allow fork syncing.
- Select Restrict who can push to matching branches.
- Optionally, to also restrict the creation of matching branches, select Restrict pushes that create matching branches.
- In the search field, search for and select the people, teams, or apps who will have permission to push to the protected branch or create a matching branch.
- Select Everyone to allow everyone with at least write permissions to the repository to force push to the branch, including those with admin permissions.
- Select Specify who can force push to allow only specific actors to force push to the branch. Then, search for and select those actors.
For more information about force pushes, see «About protected branches.»
Editing a branch protection rule
- On GitHub.com, navigate to the main page of the repository.
- Under your repository name, click
Settings. If you cannot see the «Settings» tab, select the

dropdown menu, then click Settings.
Deleting a branch protection rule
- On GitHub.com, navigate to the main page of the repository.
- Under your repository name, click
Settings. If you cannot see the «Settings» tab, select the

dropdown menu, then click Settings.