Как изменить имя ветки git

You can change the name of a branch in a repository.

About renaming branches

You can rename a branch in a repository on GitHub.com. For more information about branches, see «About branches).»

When you rename a branch on GitHub.com, any URLs that contain the old branch name are automatically redirected to the equivalent URL for the renamed branch. Branch protection policies are also updated, as well as the base branch for open pull requests (including those for forks) and draft releases. After the rename is complete, GitHub provides instructions on the repository’s home page directing contributors to update their local Git environments.

Although file URLs are automatically redirected, raw file URLs are not redirected. Also, GitHub does not perform any redirects if users perform a git pull for the previous branch name.

GitHub Actions workflows do not follow renames, so if your repository publishes an action, anyone using that action with @{old-branch-name} will break. You should consider adding a new branch with the original content plus an additional commit reporting that the branch name is deprecated and suggesting that users migrate to the new branch name.

Renaming a branch

  1. On GitHub.com, navigate to the main page of the repository.
  2. Above the list of files, click Branches.
    Branches link on overview page
  3. In the list of branches, to the right of the branch you want to rename, click .
    Pencil icon to the right of branch you want to rename
  4. Type a new name for the branch.
    Text field for typing new branch name
  5. Review the information about local environments, then click Rename branch.
    Local environment information and "Rename branch" button

Updating a local clone after a branch name changes

After you rename a branch in a repository on GitHub, any collaborator with a local clone of the repository will need to update the clone.

From the local clone of the repository on a computer, run the following commands to update the name of the default branch.

$ git branch -m OLD-BRANCH-NAME NEW-BRANCH-NAME
$ git fetch origin
$ git branch -u origin/NEW-BRANCH-NAME NEW-BRANCH-NAME
$ git remote set-head origin -a

Optionally, run the following command to remove tracking references to the old branch name.

$ git remote prune origin

Управление ветками

Теперь, когда вы уже попробовали создавать, объединять и удалять ветки, пора познакомиться с некоторыми инструментами для управления ветками, которые вам пригодятся, когда вы начнёте использовать ветки постоянно.

Команда git branch делает несколько больше, чем просто создаёт и удаляет ветки.
При запуске без параметров, вы получите простой список имеющихся у вас веток:

$ git branch
  iss53
* master
  testing

Обратите внимание на символ *, стоящий перед веткой master: он указывает на ветку, на которой вы находитесь в настоящий момент (т. е. ветку, на которую указывает HEAD).
Это означает, что если вы сейчас сделаете коммит, ветка master переместится вперёд в соответствии с вашими последними изменениями.
Чтобы посмотреть последний коммит на каждой из веток, выполните команду git branch -v:

$ git branch -v
  iss53   93b412c Fix javascript issue
* master  7a98805 Merge branch 'iss53'
  testing 782fd34 Add scott to the author list in the readme

Опции --merged и --no-merged могут отфильтровать этот список для вывода только тех веток, которые слиты или ещё не слиты в текущую ветку.
Чтобы посмотреть те ветки, которые вы уже слили с текущей, можете выполнить команду git branch --merged:

$ git branch --merged
  iss53
* master

Ветка iss53 присутствует в этом списке потому что вы ранее слили её в master.
Те ветки из этого списка, перед которыми нет символа *, можно смело удалять командой git branch -d; наработки из этих веток уже включены в другую ветку, так что ничего не потеряется.

Чтобы увидеть все ветки, содержащие наработки, которые вы пока ещё не слили в текущую ветку, выполните команду git branch --no-merged:

$ git branch --no-merged
  testing

Вы увидите оставшуюся ветку.
Так как она содержит ещё не слитые наработки, попытка удалить её командой git branch -d приведёт к ошибке:

$ git branch -d testing
error: The branch 'testing' is not fully merged.
If you are sure you want to delete it, run 'git branch -D testing'.

Если вы действительно хотите удалить ветку вместе со всеми наработками, используйте опцию -D, как указано в подсказке.

Подсказка

Если в качестве аргумента не указан коммит или ветка, то опции --merged и --no-merged покажут что уже слито или не слито с вашей текущей веткой соответственно.

Вы всегда можете указать дополнительный аргумент для вывода той же информации, но относительно указанной ветки предварительно не извлекая и не переходя на неё.

$ git checkout testing
$ git branch --no-merged master
  topicA
  featureB

Переименование ветки

Внимание

Не переименовывайте ветки, которые всё ещё используются другими участниками.
Не переименовывайте ветку в master/main/mainline, не прочитав раздел «Изменение имени главной ветки».

Предположим, у вас есть ветка с именем bad-branch-name, и вы хотите изменить её на corrected-branch-name, сохранив при этом всю историю.
Вместе с этим, вы также хотите изменить имя ветки на удалённом сервере (GitHub, GitLab или другой сервер).
Как это сделать?

Переименуйте ветку локально с помощью команды git branch --move:

$ git branch --move bad-branch-name corrected-branch-name

Ветка bad-branch-name будет переименована в corrected-branch-name, но это изменение пока только локальное.
Чтобы все остальные увидели исправленную ветку в удалённом репозитории, отправьте её туда:

$ git push --set-upstream origin corrected-branch-name

Теперь проверим, где мы сейчас находимся:

$ git branch --all
* corrected-branch-name
  main
  remotes/origin/bad-branch-name
  remotes/origin/corrected-branch-name
  remotes/origin/main

Обратите внимание, что текущая ветка corrected-branch-name, которая также присутствует и на удалённом сервере.
Однако, старая ветка всё ещё по-прежнему там, но её можно удалить с помощью команды:

$ git push origin --delete bad-branch-name

Теперь старое имя ветки полностью заменено исправленным.

Изменение имени главной ветки

Предупреждение

Изменение имени ветки, например master/main/mainline/default, сломает интеграции, службы, вспомогательные утилиты и скрипты сборки, которые использует ваш репозиторий.
Прежде чем сделать это, обязательно проконсультируйтесь с коллегами.
Также убедитесь, что вы выполнили тщательный поиск в своём репозитории и обновили все ссылки на старое имя ветки в вашем коде или скриптах.

Переименуйте локальную ветку master в main с помощью следующей команды:

$ git branch --move master main

После этого, локальной ветки master больше не существует, потому что она была переименована в ветку main.

Чтобы все остальные могли видеть новую ветку main, вам нужно отправить её в общий репозиторий.
Это делает переименованную ветку доступной в удалённом репозитории.

$ git push --set-upstream origin main

В итоге, состояние репозитория становится следующим:

$ git branch --all
* main
  remotes/origin/HEAD -> origin/master
  remotes/origin/main
  remotes/origin/master

Ваша локальная ветка master исчезла, так как она заменена веткой main.
Ветка main доступна в удалённом репозитории.
Старая ветка master всё ещё присутствует в удалённом репозитории.
Остальные участники будут продолжать использовать ветку master в качестве основы для своей работы, пока вы не совершите ряд дополнительных действий.

Теперь, для завершения перехода на новую ветку перед вами стоят следующие задачи:

  • Все проекты, которые зависят от текущего, должны будут обновить свой код и/или конфигурацию.

  • Обновите конфигурацию всех запускаемых тестов.

  • Исправьте скрипты сборки и публикации артефактов.

  • Поправьте настройки репозитория на сервере: задайте новую ветку по умолчанию, обновите правила слияния, а также прочие настройки, которые зависят от имени веток.

  • Обновите документацию, исправив ссылки, указывающие на старую ветку.

  • Слейте или отмените запросы на слияние изменений, нацеленные на старую ветку.

После того, как вы выполнили все эти задачи и уверены, что ветка main работает так же, как ветка master, вы можете удалить ветку master:

$ git push origin --delete master

Asked
11 years, 7 months ago

Viewed
4.9m times

Mateen Ulhaq's user avatar

Mateen Ulhaq

23k16 gold badges89 silver badges130 bronze badges

asked Jul 6, 2011 at 3:20

Forrest's user avatar

0

To rename the current branch:

git branch -m <newname>

To rename a branch while pointed to any branch:

git branch -m <oldname> <newname>

-m is short for --move.


To push the local branch and reset the upstream branch:

git push origin -u <newname>

To delete the remote branch:

git push origin --delete <oldname>

To create a git rename alias:

git config --global alias.rename 'branch -m'

On Windows or another case-insensitive filesystem, use -M if there are only capitalization changes in the name. Otherwise, Git will throw a «branch already exists» error.

git branch -M <newname>

Sam Denty's user avatar

Sam Denty

3,5113 gold badges27 silver badges40 bronze badges

answered Jul 6, 2011 at 3:21

siride's user avatar

siridesiride

196k4 gold badges39 silver badges61 bronze badges

14

git branch -m old_branch_name new_branch_name

The above command will change your branch name, but you have to be very careful using the renamed branch, because it will still refer to the old upstream branch associated with it, if any.

If you want to push some changes into master after your local branch is renamed into new_branch_name (example name):

git push origin new_branch_name:master (now changes will go to master branch but your local branch name is new_branch_name)

For more details, see «How to rename your local branch name in Git.»

Nick Matteo's user avatar

Nick Matteo

4,3471 gold badge21 silver badges33 bronze badges

answered Jan 21, 2013 at 9:49

Madhan Ayyasamy's user avatar

Madhan AyyasamyMadhan Ayyasamy

15.3k3 gold badges19 silver badges18 bronze badges

0

To rename your current branch:

git branch -m <newname>

answered Jun 20, 2013 at 15:05

Jonathan's user avatar

JonathanJonathan

19.9k6 gold badges64 silver badges70 bronze badges

2

Here are the steps to rename the branch:

  1. Switch to the branch which needs to be renamed
  2. git branch -m <new_name>
  3. git push origin :<old_name>
  4. git push origin <new_name>:refs/heads/<new_name>

EDIT (12/01/2017): Make sure you run command git status and check that the newly created branch is pointing to its own ref and not the older one. If you find the reference to the older branch, you need to unset the upstream using:

git branch --unset-upstream

Peter Mortensen's user avatar

answered Apr 15, 2015 at 12:50

Milind Anantwar's user avatar

Milind AnantwarMilind Anantwar

80.6k25 gold badges94 silver badges123 bronze badges

2

Rename the branch will be useful once your branch is finished. Then new stuff is coming, and you want to develop in the same branch instead of deleting it and create the new one.

From my experience, to rename a local and remote branch in Git you should do the following steps.

Quoting from Multiple States — Rename a local and remote branch in
git

1. Rename your local branch

If you are on the branch you want to rename:

git branch -m new-name

If you are on a different branch:

git branch -m old-name new-name

2. Delete the old-name remote branch and push the new-name local branch

git push origin :old-name new-name

3. Reset the upstream branch for the new-name local branch

git push origin -u new-name

Peter Mortensen's user avatar

answered Oct 14, 2016 at 3:22

trungk18's user avatar

trungk18trungk18

19.5k8 gold badges46 silver badges82 bronze badges

2

The answers so far have been correct, but here is some additional information:

One can safely rename a branch with ‘-m’ (move), but one has to be careful with ‘-M’, because it forces the rename, even if there is an existing branch with the same name already. Here is the excerpt from the ‘git-branch’ man page:

With a -m or -M option, <oldbranch> will be renamed to <newbranch>. If <oldbranch> had a corresponding reflog, it is renamed to match <newbranch>, and a reflog entry is created to remember the branch renaming. If <newbranch> exists, -M must be used to force the rename to happen.

mskfisher's user avatar

mskfisher

3,2434 gold badges34 silver badges48 bronze badges

answered Sep 24, 2013 at 13:21

Vanchev's user avatar

VanchevVanchev

1,5341 gold badge9 silver badges7 bronze badges

2

1. Rename

If it is your current branch, just do

git branch -m new_name

If it is another branch you want to rename

git branch -m old_name new_name

2. Track a new remote branch

— If your branch was pushed, then after renaming you need to delete it from the remote Git repository and ask your new local to track a new remote branch:

git push origin :old_name
git push --set-upstream origin new_name

pkamb's user avatar

pkamb

32.2k22 gold badges158 silver badges186 bronze badges

answered Dec 17, 2015 at 13:45

Oss's user avatar

OssOss

4,2022 gold badges19 silver badges35 bronze badges

1

I foolishly named a branch starting with a hyphen, and then checked out master. I didn’t want to delete my branch, I had work in it.

Neither of these worked:

git checkout -dumb-name

git checkout -- -dumb-name

"s, 's and s didn’t help either. git branch -m doesn’t work.

Here’s how I finally fixed it. Go into your working copy’s .git/refs/heads, find the filename «-dumb-name», get the hash of the branch. Then this will check it out, make a new branch with a sane name, and delete the old one.

git checkout {hash}
git checkout -b brilliant-name
git branch -d -- -dumb-name

answered Nov 9, 2013 at 7:31

Samuel Meacham's user avatar

Samuel MeachamSamuel Meacham

10.1k7 gold badges44 silver badges50 bronze badges

5

Just three steps to replicate change in name on remote as well as on GitHub:

Step 1 git branch -m old_branchname new_branchname

Step 2 git push origin :old_branchname new_branchname

Step 3 git push --set-upstream origin new_branchname

answered Mar 22, 2019 at 1:03

Hari_pb's user avatar

Hari_pbHari_pb

6,7603 gold badges43 silver badges52 bronze badges

2

To rename a branch locally:

git branch -m [old-branch] [new-branch]

Now you’ll have to propagate these changes on your remote server as well.

To push changes of the deleted old branch:

git push origin :[old-branch]

To push changes of creation of new branch:

git push origin [new-branch]

answered Aug 20, 2015 at 6:39

aliasav's user avatar

aliasavaliasav

2,9784 gold badges23 silver badges30 bronze badges

Trying to answer specifically the question (at least the title).

You can also rename the local branch, but keep tracking the old name on the remote.

git branch -m old_branch new_branch
git push --set-upstream origin new_branch:old_branch

Now, when you run git push, the remote old_branch ref is updated with your local new_branch.

You have to know and remember this configuration. But it can be useful if you don’t have the choice for the remote branch name, but you don’t like it (oh, I mean, you’ve got a very good reason not to like it !) and prefer a clearer name for your local branch.

Playing with the fetch configuration, you can even rename the local remote-reference. i.e, having a refs/remote/origin/new_branch ref pointer to the branch, that is in fact the old_branch on origin. However, I highly discourage this, for the safety of your mind.

auspicious99's user avatar

auspicious99

3,7141 gold badge41 silver badges55 bronze badges

answered May 19, 2016 at 10:39

Pierre-Olivier Vares's user avatar

Update 2023

Before we begin, make sure you’ve selected the branch you want to rename:

git checkout old-name

If you want to see all of your local branches, use the following command:

git branch --list

When you’re all clear, follow these steps:

  1. Using the Git rename branch command will require you to add an -m option to your command:

    git branch -m new-name
    
  2. You can also rename a local branch from another branch by using the following two commands:

    git checkout master
    
    git branch -m old-name new-name
    
  3. Lastly, this command will list all — both local and remote — branches to verify that it has been renamed:

    git branch -a
    

Although it isn’t possible to rename a remote branch directly, the process of renaming one involves these two easy steps:

  1. To start, you need to rename a local branch by following the previous steps.
    2.Then delete the old branch and push the new one. You can do this easily with the following command:

     git push origin :old-name new-name
    
  2. Reset the upstream branch for your new local branch, and you will be all set:

    git push origin -u new-name
    

answered Sep 28, 2020 at 13:01

S. Hesam's user avatar

S. HesamS. Hesam

4,4493 gold badges34 silver badges54 bronze badges

Rename the branch using this command:

git branch -m [old_branch_name] [new_branch_name]

-m: It renames/moves the branch. If there is already a branch, you will get an error.

If there is already a branch and you want to rename with that branch, use:

 git rename -M [old_branch_name] [new_branch_name]

For more information about help, use this command in the terminal:

git branch --help

or

man git branch

Peter Mortensen's user avatar

answered Apr 11, 2015 at 6:19

Hafiz Shehbaz Ali's user avatar

Advanced Git users can rename manually using:

Rename the old branch under .git/refs/heads to the new name

Rename the old branch under .git/logs/refs/heads to the new name

Update the .git/HEAD to point to yout new branch name

Constant's user avatar

Constant

5541 gold badge3 silver badges22 bronze badges

answered Aug 5, 2015 at 9:04

Jethik's user avatar

JethikJethik

1,8501 gold badge22 silver badges26 bronze badges

1

  1. Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

If you are on a different branch:

git branch -m old-name new-name
  1. Delete the old-name remote branch and push the new-name local branch.

git push origin :old-name new-name

  1. Reset the upstream branch for the new-name local branch.
    Switch to the branch and then:

git push origin -u new-name

Or for a fast way to do that, you can use these 3 steps:

# Rename branch locally

git branch -m old_branch new_branch  

# Delete the old remote branch

git push origin :old_branch  

# Push the new branch, set local branch to track the new remote

git push --set-upstream origin new_branch   

Referance: https://www.w3docs.com/snippets/git/how-to-rename-git-local-and-remote-branches.html

Major's user avatar

Major

5445 silver badges18 bronze badges

answered Apr 8, 2018 at 5:49

badarshahzad's user avatar

badarshahzadbadarshahzad

1,21716 silver badges25 bronze badges

0

To rename your current branch to a new branch name :

git branch -m <new_name>

This will set the new name for the current branch you are working with.


To re-name another branch :

git branch -m <old_name> <new_name>

Here you have to provide the old branch name and the new branch name.

answered Apr 25, 2022 at 18:43

loopassembly's user avatar

loopassemblyloopassembly

1,6151 gold badge11 silver badges20 bronze badges

Here are three steps: A command that you can call inside your terminal and change branch name.

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

If you need more: step-by-step, How To Change Git Branch Name is a good article about that.

Peter Mortensen's user avatar

answered May 10, 2016 at 18:04

Hazarapet Tunanyan's user avatar

1

Probably as mentioned by others, this will be a case mismatch in branch naming.

If you have such a situation, I can guess that you’re on Windows which will also lead you to:

$ git branch -m CaseSensitive casesensitive
fatal: A branch named 'casesensitive' already exists.

Then you have to do an intermediate step:

$ git branch -m temporary
$ git branch -m casesensitive

Nothing more.

Peter Mortensen's user avatar

answered May 25, 2015 at 11:52

P4C's user avatar

P4CP4C

5075 silver badges10 bronze badges

2

Changing the branch locally is quite easy…

If you are on the branch you want to change the name for, simply do this:

git branch -m my_new_branch

Otherwise, if you are on master or any other branch other than the one you’d like to change the name, simply do:

git branch -m my_old_branch my_new_branch

Also, I create the image below to show this in action on a command line. In this case, you are on master branch, for example:

Change branch name locally

Peter Mortensen's user avatar

answered Jul 4, 2017 at 14:01

Alireza's user avatar

AlirezaAlireza

98k27 gold badges266 silver badges171 bronze badges

To rename the current branch (except for detached HEAD state) you can also use this alias:

[alias]
    mvh = !sh -c 'git branch -m `git rev-parse --abbrev-ref HEAD` $1'

Peter Mortensen's user avatar

answered Sep 2, 2014 at 17:25

dentuzhik's user avatar

dentuzhikdentuzhik

7328 silver badges17 bronze badges

Since you do not want to push the branch to a remote server, this example will be useful:

Let’s say you have an existing branch called «my-hot-feature,» and you want to rename it to «feature-15.»

First, you want to change your local branch. This couldn’t be easier:

git branch -m my-hot-feature feature-15

For more information, you can visit Locally and Remotely Renaming a Branch in Git.

tagurit's user avatar

tagurit

4786 silver badges13 bronze badges

answered Oct 27, 2015 at 10:17

Tanah's user avatar

TanahTanah

4494 silver badges8 bronze badges

If you are willing to use SourceTree (which I strongly recommend), you can right click your branch and chose ‘Rename’.

enter image description here

Pang's user avatar

Pang

9,365146 gold badges85 silver badges121 bronze badges

answered May 26, 2017 at 11:14

Marcin Szymczak's user avatar

Marcin SzymczakMarcin Szymczak

10.9k5 gold badges54 silver badges62 bronze badges

Another option is not to use the command line at all. Git GUI clients such as SourceTree take away much of the syntactical learning curve / pain that causes questions such as this one to be amongst the most viewed on Stack Overflow.

In SourceTree, right click on any local branch in the «Branches» pane on the left and select «Rename …».

Peter Mortensen's user avatar

answered Mar 8, 2015 at 16:13

Steve Chambers's user avatar

Steve ChambersSteve Chambers

35.5k21 gold badges151 silver badges203 bronze badges

2

A simple way to do it:

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

For more, see this.

Peter Mortensen's user avatar

answered Mar 27, 2018 at 16:00

Nomade's user avatar

NomadeNomade

1,7302 gold badges18 silver badges33 bronze badges

Git version 2.9.2

If you want to change the name of the local branch you are on:

git branch -m new_name

If you want to change the name of a different branch:

git branch -m old_name new_name

If you want to change the name of a different branch to a name that already exists:

git branch -M old_name new_name_that_already_exists

Note: The last command is destructive and will rename your branch, but you will lose the old branch with that name and those commits because branch names must be unique.

Peter Mortensen's user avatar

answered Sep 22, 2016 at 0:03

nikkypx's user avatar

nikkypxnikkypx

1,86517 silver badges12 bronze badges

If you want to change the name of the current branch, run:

git branch -m [old_branch] [new_branch]

If you want to delete the old remote branch, run:

git push origin :[old_branch]

If you want to delete the old remote branch and create a new remote branch, run:

git push origin :old_branch new_branch

2Toad's user avatar

2Toad

14.6k7 gold badges42 silver badges42 bronze badges

answered Jan 31, 2017 at 15:53

Arif's user avatar

ArifArif

3312 silver badges7 bronze badges

Actually you have three steps because the local branch has a duplicate on the server so we have one step for local on two steps on the server:

  1. Rename local: just use the following command to rename your current branch, even you checked it out:
    git branch -m <old-branch-name> <new-branch-name>
    
  2. Delete the server one: use the following command to delete the old name branch on the server:
    git push <remote-name[origin by default]> :<old-branch-name>
    
  3. Push the new one: now it’s time to push the new branch named on the server:
    git push -u <new-branch-name>
    

answered Aug 5, 2020 at 8:24

AmerllicA's user avatar

AmerllicAAmerllicA

26.7k14 gold badges125 silver badges148 bronze badges

2

Git branch rename can be done by using:

  1. git branch -m oldBranch newBranch

  2. git branch -M oldBranch ExistingBranch

The difference between -m and -M:

-m: if you’re trying to rename your branch with an existing branch name using -m.
It will raise an error saying that the branch already exists. You need to give unique name.

But,

-M: this will help you to force rename with a given name, even it is exists. So an existing branch will overwrite entirely with it…

Here is a Git terminal example,

mohideen@dev:~/project/myapp/sunithamakeup$ git branch
  master
  master0
  new_master
  test
* test1
mohideen@dev:~/project/myapp/sunithamakeup$ git branch -m test1 test
fatal: A branch named 'test' already exists.
mohideen@dev:~/project/myapp/sunithamakeup$ git branch -M test1 test
mohideen@dev:~/project/myapp/sunithamakeup$ git branch
  master
  master0
  new_master
* test
mohideen@dev:~/project/myapp/sunithamakeup$

Peter Mortensen's user avatar

answered Sep 1, 2017 at 6:59

Mohideen bin Mohammed's user avatar

All of the previous answers are talking about git branch -m. Of course, it’s easy to operate, but for me, it may be a little hard to remember another Git command. So I tried to get the work done by the command I was familiar with. Yeah, you may guessed it.

I use git branch -b <new_branch_name>. And if you don’t want to save the old branch now you can execute git branch -D <old_branch_name> to remove it.

I know it may be a little tedious, but it’s easier to understand and remember. I hope it‘s helpful for you.

answered Aug 29, 2017 at 2:16

Dai Kaixian's user avatar

Dai KaixianDai Kaixian

1,0272 gold badges14 silver badges24 bronze badges

0

For Git GUI users it couldn’t be much simpler.
In Git GUI, choose the branch name from the drop down list in the «Rename Branch» dialog box created from the menu item Branch:Rename, type a New Name, and click «Rename». I have highlighted where to find the drop down list.

Rename a local Git branch

answered Sep 3, 2018 at 15:58

Ivan's user avatar

IvanIvan

4,17334 silver badges27 bronze badges

Окт 09, 2021

Olha L.

3хв. читання

Если вы работаете в Git, то вам, наверняка, знакома ситуация, когда ветка случайно была названа неправильно или просто нужно сменить её название, чтобы лучше организовать проект. В любом случае это довольно распространённое явление, когда вам нужно переименовать ветку Git, локальную или удалённую. В этом руководстве мы покажем, как это сделать. А также кратко объясним, что такое Git-репозиторий и некоторые полезные команды Git.

Установите и используйте Git вместе с мощным и надёжным хостингом от Hostinger.

Как Переименовать Локальную Ветку Git?

Прежде чем мы начнём, убедитесь, что вы выбрали ветку, которую хотите переименовать:

git checkout staroje-imia

Если вы хотите посмотреть все локальные ветки, используйте следующую команду:

git branch --list

Разобравшись с этим, выполните следующее действие:

  1. Чтобы переименовать текущую ветку Git, добавьте к команде опцию -m:
    git branch -m novoje-imia
  1. Вы также можете переименовать локальную ветку, находясь на другой ветке, используя следующие две команды:
    git checkout master
    git branch -m staroje-imia novoje-imia
  1. Наконец, эта команда выведет список всех, как локальных, так и удалённых веток. Убедитесь, что ветка с новым названием есть в этом списке.
    git branch -a

Как Переименовать Удалённую Ветку Git?

Хотя удалённую ветку и нельзя переименовать напрямую, процесс довольно простой и состоит лишь с трёх шагов:

  1. Для начала вам нужно будет переименовать локальную ветку, следуя инструкции выше.
  2. Затем удалите старую ветку и запуште новую. Сделать это можно с помощью следующих простых команд:
    git push origin --delete staroje-imia
    git push origin :staroje-imia novoje-imia
  1. Выгрузите новую ветку и «закрепите» её за локальной:
    git push origin -u novoje-imia

Как Создать Новую Локальную Ветку Git?

Прежде чем создавать новую ветку, обратите внимание, что каждый репозиторий, о котором мы будем говорить дальше, содержит основную стабильную ветку (master branch), содержащую изменения, готовые для продакшена. Когда вы создаёте ветку, всё, что делает Git, это создаёт новый указатель.

Мы можем создать новую локальную ветку, выполнив следующие шаги.

  1. Перейдите в корень вашей master branch:
    cd nazvanije-repozitorija
  1. Вы можете создать ветку из главной ветки с помощью следующей команды:
    git branch imia-novoj-vetki

    Или же вы можете создать новую ветку и переключиться на неё:

    git checkout -b imia-novoj-vetki

    Вы также можете клонировать ветку и затем перейти на неё:

    git checkout -b imia-novoj-vetki origin/imia-novoj-vetki
  1. Переключитесь на новую ветку:
    git checkout imia-novoj-vetki
  1. Наконец, убедитесь, что вы находитесь в новой ветке:
    git status

Как Удалить Локальную Ветку Git?

Чтобы удалить локальную ветку, вы можете использовать одну из следующих команд Git:

git branch -d imia-vetki
git branch -D imia-vetki

Опция -d (–delete) удалит локальную ветку, если вы уже запушили и смержили её с удалённой веткой.

Опция -D (–delete –force) удалит локальную ветку независимо от того, успели вы запушить и смержить её с удалённой веткой или нет.

Как Удалить Удалённую Ветку Git?

Вы также можете удалить удалённую ветку и указать, как название удалённого репозитория, так и ветки. В большинстве случаев, название удалённого сервера по умолчанию — «origin«. Команда будет выглядеть так:

git push imia_udalennogo_repozitorija --delete imia-vetki
git push imia_udalennogo_repozitorija :imia-vetki

Осмотр и Сравнение

В Git вы можете просмотреть все внесённые вами изменения в любое время. Чтобы увидеть эти изменения, введите следующую команду:

git log

Или, для более подробной информации:

git log --summary

Что Такое Ветка Git? 

Git — это распределённая система контроля версий (DVCS), в которой все члены команды имеют доступ к полной версии проекта. Её главная задача — помогать в управлении проектам, сделать процесс разработки эффективным, гибким и безопасным.

Ветки — это отдельные линии развития вашего проекта. Они позволяют работать параллельно с master веткой, при этом не влияя на неё. Когда же ваша часть кода готова, вы можете выполнить слияние, или мерж.

Ветвление Git позволяет создавать, удалять и смотреть другие ветки. Кроме того, ветка действует как указатель на моментальный снимок изменений (snapshot), которые вы внесли или хотите внести в файлы проекта. Это полезно в ситуациях, когда вы хотите добавить дополнительную функцию или устранить баг.

Ветка не только инкапсулирует изменения, но также гарантирует, что нестабильный код не попадёт к файлам основного проекта. Как только вы закончите обновлять код в ветке, вы сможете смержить изменения в ветку master.

Что Такое Git-репозиторий?

Репозиторий работает как папка для проекта. Он содержит все файлы и хранит их историю изменений. Репозитории могут быть частными или общедоступными. Вы также можете делиться ими с другими людьми в вашей организации.

Когда вы инициализируете Git-репозиторий, в корне папки проекта автоматически создаётся каталог .git/. Здесь Git отслеживает изменения в файлах проекта, сохраняет объекты, ссылки и дополнительную информацию для управления репозиториями.

Будьте осторожны, ведь если вы случайно удалите папку .git/, вы потеряете всю истерию вашего проекта.

Как Клонировать Удалённый Репозиторий?

Чтобы клонировать репозиторий, мы будем использовать команду Git clone. Кроме того, вам также необходимо указать URL-адрес репозитория:

  1. Вы можете клонировать главную ветку (master branch) из удалённого репозитория с помощью HTTPS или SSH.
    Для HTTPS:

    git clone https://github.com/imia-polzovatelia/imia-vashego-repozitorija.git

    Для SSH:

    git clone ssh://github.com/imia-polzovatelia/imia-vashego-repozitorija.git
  2. Чтобы перейти в корень клонированного репозитория, вы можете использовать команду cd:
    cd vashi_prilozhenija
  1. Проверить состояние ветки можно с помощью простой команды Git:
    git status

Дополнительная Информация о Git

Если вам нужна информация о том, как пользоваться Git, обратитесь к официальной документации, доступной онлайн. Кроме того, рекомендуем ознакомиться с нашими руководствами об основных командах Git, о том, как использовать PuTTY SSH-терминал для подключения к вашей учётной записи хостинга или VPS-серверу, как установить Git (англ) в Ubuntu, а также подробное руководство по GitHub.

Итоги

Теперь вы знаете, как управлять ветками с помощью различных команд. Вы можете создать или переименовать ветку Git, посмотреть список существующих веток или удалить какую-то из них.

Мы надеемся, что вам понравилось это руководство. И с нетерпением ждём вас в следующем!

Author

Ольга вже близько восьми років працює менеджером у сфері IT, три з яких вона займається SEO. Написання технічних завдань та інструкцій — один з її основних обов’язків. Її хобі — дізнаватися щось нове і створювати цікаві та корисні статті про сучасні технології, веброзробку, мови програмування, пошукову оптимізацію сайтів та багато іншого.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить имя вайфая ростелеком
  • Как изменить имя вайфая на телефоне
  • Как изменить имя вайфая на роутере
  • Как изменить имя вайфая белтелеком
  • Как изменить имя вайфай сети

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии