Как изменить remote origin git

I have a repo (origin) on a USB key that I cloned on my hard drive (local). I moved "origin" to a NAS and successfully tested cloning it from here. I would like to know if I can change th...

You can

git remote set-url origin new.git.url/here

See git help remote. You also can edit .git/config and change the URLs there.

You’re not in any danger of losing history unless you do something very silly (and if you’re worried, just make a copy of your repo, since your repo is your history.)

Matthias Braun's user avatar

answered Mar 12, 2010 at 12:55

hobbs's user avatar

hobbshobbs

217k18 gold badges206 silver badges286 bronze badges

20

git remote -v
# View existing remotes
# origin  https://github.com/user/repo.git (fetch)
# origin  https://github.com/user/repo.git (push)

git remote set-url origin https://github.com/user/repo2.git
# Change the 'origin' remote's URL

git remote -v
# Verify new remote URL
# origin  https://github.com/user/repo2.git (fetch)
# origin  https://github.com/user/repo2.git (push)

Changing a remote’s URL

Zombo's user avatar

answered Oct 10, 2013 at 14:43

Utensil's user avatar

UtensilUtensil

16.3k1 gold badge16 silver badges10 bronze badges

4

git remote set-url {name} {url}

git remote set-url origin https://github.com/myName/GitTest.git

Thavas Antonio's user avatar

answered Dec 28, 2015 at 4:53

최봉재's user avatar

최봉재최봉재

3,9433 gold badges16 silver badges21 bronze badges

1

Change Host for a Git Origin Server

from: http://pseudofish.com/blog/2010/06/28/change-host-for-a-git-origin-server/

Hopefully this isn’t something you need to do. The server that I’ve been using to collaborate on a few git projects with had the domain name expire. This meant finding a way of migrating the local repositories to get back in sync.

Update: Thanks to @mawolf for pointing out there is an easy way with recent git versions (post Feb, 2010):

git remote set-url origin ssh://newhost.com/usr/local/gitroot/myproject.git

See the man page for details.

If you’re on an older version, then try this:

As a caveat, this works only as it is the same server, just with different names.

Assuming that the new hostname is newhost.com, and the old one was oldhost.com, the change is quite simple.

Edit the .git/config file in your working directory. You should see something like:

[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = ssh://oldhost.com/usr/local/gitroot/myproject.git

Change oldhost.com to newhost.com, save the file and you’re done.

From my limited testing (git pull origin; git push origin; gitx) everything seems in order. And yes, I know it is bad form to mess with git internals.

Craig McQueen's user avatar

Craig McQueen

40.9k28 gold badges126 silver badges179 bronze badges

answered Feb 15, 2011 at 2:52

yoda's user avatar

yodayoda

4,7593 gold badges19 silver badges9 bronze badges

2

This is very easy and simple; just follow these instructions.

  1. For adding or changing the remote origin:
    git remote set-url origin githubrepurl
    
  2. To see which remote URL you have currently in this local repository:
    git remote show origin
    

Matthias Braun's user avatar

answered Feb 1, 2022 at 21:33

Mithun Rana's user avatar

Mithun RanaMithun Rana

1,2261 gold badge7 silver badges10 bronze badges

1

Switching remote URLs

Open Terminal.

Ist Step:— Change the current working directory to your local project.

2nd Step:— List your existing remotes in order to get the name of the remote you want to change.

git remote -v

origin  https://github.com/USERNAME/REPOSITORY.git (fetch)

origin  https://github.com/USERNAME/REPOSITORY.git (push)

Change your remote’s URL from HTTPS to SSH with the git remote set-url command.

3rd Step:git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

4th Step:— Now Verify that the remote URL has changed.

git remote -v
Verify new remote URL

origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
origin  git@github.com:USERNAME/REPOSITORY.git (push)

Community's user avatar

answered Dec 8, 2017 at 11:01

VIKAS KOHLI's user avatar

VIKAS KOHLIVIKAS KOHLI

7,8763 gold badges49 silver badges57 bronze badges

2

git remote set-url origin git://new.location

(alternatively, open .git/config, look for [remote "origin"], and edit the url = line.

You can check it worked by examining the remotes:

git remote -v
# origin  git://new.location (fetch)
# origin  git://new.location (push)

Next time you push, you’ll have to specify the new upstream branch, e.g.:

git push -u origin master

See also: GitHub: Changing a remote’s URL

answered Apr 26, 2015 at 23:13

Zaz's user avatar

ZazZaz

45.4k11 gold badges82 silver badges97 bronze badges

2

As seen here,

$ git remote rm origin
$ git remote add origin git@github.com:aplikacjainfo/proj1.git
$ git config master.remote origin
$ git config master.merge refs/heads/master

trashgod's user avatar

trashgod

203k29 gold badges242 silver badges1028 bronze badges

answered Apr 2, 2020 at 8:24

Zahid Hassan Shaikot's user avatar

3

  1. remove origin using command on gitbash
    git remote rm origin
  2. And now add new Origin using gitbash
    git remote add origin (Copy HTTP URL from your project repository in bit bucket)
    done

answered Jun 24, 2016 at 11:10

Sunil Chaudhary's user avatar

3

First you need to type this command to view existing remotes

git remote -v

Then second you need to type this command to Change the ‘origin’ remote’s URL

git remote set-url origin <paste your GitHub URL>

arnavakhoury's user avatar

answered May 1, 2022 at 23:05

Abdullah Al Mahmud's user avatar

Write the below command from your repo terminal:

git remote set-url origin git@github.com:<username>/<repo>.git

Refer this link for more details about changing the url in the remote.

answered Dec 19, 2019 at 9:25

viveknaskar's user avatar

viveknaskarviveknaskar

2,0161 gold badge19 silver badges34 bronze badges

0

To check git remote connection:

git remote -v

Now, set the local repository to remote git:

git remote set-url origin https://NewRepoLink.git

Now to make it upstream or push use following code:

git push --set-upstream origin master -f

answered Dec 18, 2018 at 5:22

Anupam Maurya's user avatar

1

Navigate to the project root of the local repository and check for existing remotes:

git remote -v

If your repository is using SSH you will see something like:

> origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
> origin  git@github.com:USERNAME/REPOSITORY.git (push)

And if your repository is using HTTPS you will see something like:

> origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin  https://github.com/USERNAME/REPOSITORY.git (push)

Changing the URL is done with git remote set-url. Depending on the output of git remote -v, you can change the URL in the following manner:

In case of SSH, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin git@github.com:USERNAME/NEW_REPOSITORY.git

And in case of HTTPS, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin https://github.com/USERNAME/NEW_REPOSITORY.git

NOTE: If you’ve changed your GitHub username, you can follow the same process as above to update the change in the username associated with your repository. You would only have to update the USERNAME in the git remote set-url command.

answered Aug 17, 2020 at 20:03

Saurabh's user avatar

SaurabhSaurabh

4,0962 gold badges28 silver badges39 bronze badges

if you cloned your local will automatically consist,

remote URL where it gets cloned.

you can check it using git remote -v

if you want to made change in it,

git remote set-url origin https://github.io/my_repo.git

here,

origin — your branch

if you want to overwrite existing branch you can still use it.. it will override your existing … it will do,

git remote remove url
and 
git remote add origin url

for you…

answered Jul 31, 2017 at 7:33

Mohideen bin Mohammed's user avatar

1

I worked:

git remote set-url origin <project>

answered May 6, 2018 at 18:24

Diego Santa Cruz Mendezú's user avatar

In the Git Bash, enter the command:

git remote set-url origin https://NewRepoLink.git

Enter the Credentials

Done

answered Apr 25, 2017 at 9:48

devDeejay's user avatar

devDeejaydevDeejay

5,3551 gold badge26 silver badges38 bronze badges

You have a lot of ways to do that:

Console

git remote set-url origin [Here new url] 

Just be sure that you’ve opened it in a place where a repository is.

Config

It is placed in .git/config (same folder as repository)

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = [Here new url]  <------------------------------------
...

TortoiseGit

Step 1 - open settings

Step 2 - change url

Then just edit URL.

SourceTree

  1. Click on the «Settings» button on the toolbar to open the Repository Settings window.

  2. Click «Add» to add a remote repository path to the repository. A «Remote details» window will open.

  3. Enter a name for the remote path.

  4. Enter the URL/Path for the remote repository

  5. Enter the username for the hosting service for the remote repository.

  6. Click ‘OK’ to add the remote path.

  7. Back on the Repository Settings window, click ‘OK’. The new remote path should be added on the repository now.

  8. If you need to edit an already added remote path, just click the ‘Edit’ button. You should be directed to the «Remote details» window where you can edit the details (URL/Path/Host Type) of the remote path.

  9. To remove a remote repository path, click the ‘Remove’ button

enter image description here

enter image description here

ref. Support

answered Apr 2, 2019 at 13:37

Przemek Struciński's user avatar

For me, the accepted answer worked only in the case of fetch but not pull. I did the following to make it work for push as well.

git remote set-url --push origin new.git.url/here

So to update the fetch URL:

git remote set-url origin new.git.url/here

To update the pull URL:

git remote set-url --push origin new.git.url/here

answered May 6, 2021 at 11:27

Shailendra Madda's user avatar

Shailendra MaddaShailendra Madda

20.1k15 gold badges95 silver badges137 bronze badges

Change remote git URI to git@github.com rather than https://github.com

git remote set-url origin git@github.com:<username>/<repo>.git

Example:

git remote set-url origin git@github.com:Chetabahana/my_repo_name.git

The benefit is that you may do git push automatically when you use ssh-agent :

#!/bin/bash

# Check ssh connection
ssh-add -l &>/dev/null
[[ "$?" == 2 ]] && eval `ssh-agent`
ssh-add -l &>/dev/null
[[ "$?" == 1 ]] && expect $HOME/.ssh/agent

# Send git commands to push
git add . && git commit -m "your commit" && git push -u origin master

Put a script file $HOME/.ssh/agent to let it runs ssh-add using expect as below:

#!/usr/bin/expect -f
set HOME $env(HOME)
spawn ssh-add $HOME/.ssh/id_rsa
expect "Enter passphrase for $HOME/.ssh/id_rsa:"
send "<my_passphrase>n";
expect "Identity added: $HOME/.ssh/id_rsa ($HOME/.ssh/id_rsa)"
interact

BenKoshy's user avatar

BenKoshy

32k14 gold badges103 silver badges78 bronze badges

answered May 25, 2019 at 11:54

eQ19's user avatar

eQ19eQ19

9,5303 gold badges62 silver badges76 bronze badges

To change the remote upstream:
git remote set-url origin <url>


To add more upstreams:
git remote add newplace <url>

So you can choose where to work
git push origin <branch> or git push newplace <branch>

answered Feb 28, 2020 at 13:43

Anderson Cossul's user avatar

0

You can change the url by editing the config file.
Go to your project root:

nano .git/config

Then edit the url field and set your new url.
Save the changes. You can verify the changes by using the command.

git remote -v 

answered Feb 7, 2020 at 4:24

Abhi Das's user avatar

Abhi DasAbhi Das

50110 silver badges11 bronze badges

An alternative approach is to rename the ‘old’ origin (in the example below I name it simply old-origin) and adding a new one. This might be the desired approach if you still want to be able to push to the old origin every now and then:

git remote rename origin old-origin
git remote add origin git@new-git-server.com>:<username>/<projectname>.git

And in case you need to push your local state to the new origin:

git push -u origin --all
git push -u origin --tags

answered Sep 20, 2020 at 12:25

j-i-l's user avatar

j-i-lj-i-l

9,7862 gold badges49 silver badges69 bronze badges

If you’re using TortoiseGit then follow the below steps:

  1. Go to your local checkout folder and right click to go to TortoiseGit -> Settings
  2. In the left pane choose Git -> Remote
  3. In the right pane choose origin
  4. Now change the URL text box value to where ever your new remote repository is

Your branch and all your local commits will remain intact and you can keep working as you were before.

Don't Panic's user avatar

Don’t Panic

40.8k10 gold badges61 silver badges78 bronze badges

answered Aug 20, 2017 at 15:14

Vipul bhojwani's user avatar

0

It will work fine, you can try this

For SSH:

command: git remote set-url origin <ssh_url>

example: git remote set-url origin git@github.com:username/rep_name.git

For HTTPS:

command: git remote set-url origin <https_url>

example: git remote set-url origin https://github.com/username/REPOSITORY.git

answered Dec 26, 2022 at 7:51

MD. SHIFULLAH's user avatar

Removing a remote

Use the git remote rm command to remove a remote URL from your repository.

    $ git remote -v
    # View current remotes
    > origin  https://github.com/OWNER/REPOSITORY.git (fetch)
    > origin  https://github.com/OWNER/REPOSITORY.git (push)
    > destination  https://github.com/FORKER/REPOSITORY.git (fetch)
    > destination  https://github.com/FORKER/REPOSITORY.git (push)

    $ git remote rm destination
    # Remove remote
    $ git remote -v
    # Verify it's gone
    > origin  https://github.com/OWNER/REPOSITORY.git (fetch)
    > origin  https://github.com/OWNER/REPOSITORY.git (push)

answered Jun 6, 2020 at 11:05

Tayyab Roy's user avatar

Tayyab RoyTayyab Roy

4235 silver badges7 bronze badges

If you would like to set the username and password as well in the origin url, you can follow the below steps.

Exporting the password in a variable would avoid issues with special characters.

Steps:

export gituser='<Username>:<password>@'
git remote set-url origin https://${gituser}<gitlab_repo_url> 
git push origin <Branch Name>

answered Mar 3, 2021 at 5:52

Rajesh Somasundaram's user avatar

check your privilege

in my case i need to check my username

i have two or three repository with seperate credentials.

problem is my permission i have two private git server and repositories

this second account is admin of that new repo and first one is my default user account and i should grant permission to first

answered Feb 6, 2020 at 16:35

saber tabatabaee yazdi's user avatar

(Only Windows PS) To change a server/protocol recursively in all local repos

Get-ChildItem -Directory -Recurse -Depth [Number] -Hidden -name | %{$_.replace(".git","")} | %{git -C $_ remote set-url origin $(git -C $_ remote get-url origin).replace("[OLD SERVER]", "[NEW SERVER]")}

answered May 17, 2021 at 10:05

bruegth's user avatar

bruegthbruegth

3583 silver badges12 bronze badges

For those who want to make this change from Visual Studio 2019

Open Team Explorer (Ctrl+M)

Home -> Settings

Git -> Repository Settings

Remotes -> Edit

enter image description here

answered Oct 25, 2019 at 17:53

Dinch's user avatar

DinchDinch

5284 silver badges9 bronze badges

Adding a remote repository

To add a new remote, use the git remote add command on the terminal, in the directory your repository is stored at.

The git remote add command takes two arguments:

  • A remote name, for example, origin
  • A remote URL, for example, https://github.com/user/repo.git

For example:

$ git remote add origin https://github.com/USER/REPO.git
# Set a new remote

$ git remote -v
# Verify new remote
> origin  https://github.com/USER/REPO.git (fetch)
> origin  https://github.com/USER/REPO.git (push)

For more information on which URL to use, see «About remote repositories.»

Troubleshooting: Remote origin already exists

This error means you’ve tried to add a remote with a name that already exists in your local repository.

$ git remote add origin https://github.com/octocat/Spoon-Knife.git
> fatal: remote origin already exists.

To fix this, you can:

  • Use a different name for the new remote.
  • Rename the existing remote repository before you add the new remote. For more information, see «Renaming a remote repository» below.
  • Delete the existing remote repository before you add the new remote. For more information, see «Removing a remote repository» below.

Changing a remote repository’s URL

The git remote set-url command changes an existing remote repository URL.

The git remote set-url command takes two arguments:

  • An existing remote name. For example, origin or upstream are two common choices.
  • A new URL for the remote. For example:
    • If you’re updating to use HTTPS, your URL might look like:
      https://github.com/USERNAME/REPOSITORY.git
    • If you’re updating to use SSH, your URL might look like:
      git@github.com:USERNAME/REPOSITORY.git

Switching remote URLs from SSH to HTTPS

  1. Open TerminalTerminalGit Bash.
  2. Change the current working directory to your local project.
  3. List your existing remotes in order to get the name of the remote you want to change.
    $ git remote -v
    > origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
    > origin  git@github.com:USERNAME/REPOSITORY.git (push)
  4. Change your remote’s URL from SSH to HTTPS with the git remote set-url command.
    $ git remote set-url origin https://github.com/USERNAME/REPOSITORY.git
  5. Verify that the remote URL has changed.
    $ git remote -v
    # Verify new remote URL
    > origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
    > origin  https://github.com/USERNAME/REPOSITORY.git (push)

The next time you git fetch, git pull, or git push to the remote repository, you’ll be asked for your GitHub username and password. When Git prompts you for your password, enter your personal access token. Alternatively, you can use a credential helper like Git Credential Manager. Password-based authentication for Git has been removed in favor of more secure authentication methods. For more information, see «Creating a personal access token.»

You can use a credential helper so Git will remember your GitHub username and personal access token every time it talks to GitHub.

Switching remote URLs from HTTPS to SSH

  1. Open TerminalTerminalGit Bash.
  2. Change the current working directory to your local project.
  3. List your existing remotes in order to get the name of the remote you want to change.
    $ git remote -v
    > origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
    > origin  https://github.com/USERNAME/REPOSITORY.git (push)
  4. Change your remote’s URL from HTTPS to SSH with the git remote set-url command.
    $ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
  5. Verify that the remote URL has changed.
    $ git remote -v
    # Verify new remote URL
    > origin  git@github.com: USERNAME/REPOSITORY.git (fetch)
    > origin  git@github.com: USERNAME/REPOSITORY.git (push)

Troubleshooting: No such remote ‘[name]’

This error means that the remote you tried to change doesn’t exist:

$ git remote set-url sofake https://github.com/octocat/Spoon-Knife
> fatal: No such remote 'sofake'

Check that you’ve correctly typed the remote name.

Renaming a remote repository

Use the git remote rename command to rename an existing remote.

The git remote rename command takes two arguments:

  • An existing remote name, for example, origin
  • A new name for the remote, for example, destination

Example of renaming a remote repository

These examples assume you’re cloning using HTTPS, which is recommended.

$ git remote -v
# View existing remotes
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)

$ git remote rename origin destination
# Change remote name from 'origin' to 'destination'

$ git remote -v
# Verify remote's new name
> destination  https://github.com/OWNER/REPOSITORY.git (fetch)
> destination  https://github.com/OWNER/REPOSITORY.git (push)

Troubleshooting: Could not rename config section ‘remote.[old name]’ to ‘remote.[new name]’

This error means that the old remote name you typed doesn’t exist.

You can check which remotes currently exist with the git remote -v command:

$ git remote -v
# View existing remotes
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)

Troubleshooting: Remote [new name] already exists

This error means that the remote name you want to use already exists. To solve this, either use a different remote name, or rename the original remote.

Removing a remote repository

Use the git remote rm command to remove a remote URL from your repository.

The git remote rm command takes one argument:

  • A remote name, for example, destination

Removing the remote URL from your repository only unlinks the local and remote repositories. It does not delete the remote repository.

Example of removing a remote repository

These examples assume you’re cloning using HTTPS, which is recommended.

$ git remote -v
# View current remotes
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)
> destination  https://github.com/FORKER/REPOSITORY.git (fetch)
> destination  https://github.com/FORKER/REPOSITORY.git (push)

$ git remote rm destination
# Remove remote
$ git remote -v
# Verify it's gone
> origin  https://github.com/OWNER/REPOSITORY.git (fetch)
> origin  https://github.com/OWNER/REPOSITORY.git (push)

Note: git remote rm does not delete the remote repository from the server. It simply
removes the remote and its references from your local repository.

Troubleshooting: Could not remove config section ‘remote.[name]’

This error means that the remote you tried to delete doesn’t exist:

$ git remote rm sofake
> error: Could not remove config section 'remote.sofake'

Check that you’ve correctly typed the remote name.

Further reading

  • «Working with Remotes» from the Pro Git book

You can

git remote set-url origin new.git.url/here

See git help remote. You also can edit .git/config and change the URLs there.

You’re not in any danger of losing history unless you do something very silly (and if you’re worried, just make a copy of your repo, since your repo is your history.)

Matthias Braun's user avatar

answered Mar 12, 2010 at 12:55

hobbs's user avatar

hobbshobbs

217k18 gold badges206 silver badges286 bronze badges

20

git remote -v
# View existing remotes
# origin  https://github.com/user/repo.git (fetch)
# origin  https://github.com/user/repo.git (push)

git remote set-url origin https://github.com/user/repo2.git
# Change the 'origin' remote's URL

git remote -v
# Verify new remote URL
# origin  https://github.com/user/repo2.git (fetch)
# origin  https://github.com/user/repo2.git (push)

Changing a remote’s URL

Zombo's user avatar

answered Oct 10, 2013 at 14:43

Utensil's user avatar

UtensilUtensil

16.3k1 gold badge16 silver badges10 bronze badges

4

git remote set-url {name} {url}

git remote set-url origin https://github.com/myName/GitTest.git

Thavas Antonio's user avatar

answered Dec 28, 2015 at 4:53

최봉재's user avatar

최봉재최봉재

3,9433 gold badges16 silver badges21 bronze badges

1

Change Host for a Git Origin Server

from: http://pseudofish.com/blog/2010/06/28/change-host-for-a-git-origin-server/

Hopefully this isn’t something you need to do. The server that I’ve been using to collaborate on a few git projects with had the domain name expire. This meant finding a way of migrating the local repositories to get back in sync.

Update: Thanks to @mawolf for pointing out there is an easy way with recent git versions (post Feb, 2010):

git remote set-url origin ssh://newhost.com/usr/local/gitroot/myproject.git

See the man page for details.

If you’re on an older version, then try this:

As a caveat, this works only as it is the same server, just with different names.

Assuming that the new hostname is newhost.com, and the old one was oldhost.com, the change is quite simple.

Edit the .git/config file in your working directory. You should see something like:

[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = ssh://oldhost.com/usr/local/gitroot/myproject.git

Change oldhost.com to newhost.com, save the file and you’re done.

From my limited testing (git pull origin; git push origin; gitx) everything seems in order. And yes, I know it is bad form to mess with git internals.

Craig McQueen's user avatar

Craig McQueen

40.9k28 gold badges126 silver badges179 bronze badges

answered Feb 15, 2011 at 2:52

yoda's user avatar

yodayoda

4,7593 gold badges19 silver badges9 bronze badges

2

This is very easy and simple; just follow these instructions.

  1. For adding or changing the remote origin:
    git remote set-url origin githubrepurl
    
  2. To see which remote URL you have currently in this local repository:
    git remote show origin
    

Matthias Braun's user avatar

answered Feb 1, 2022 at 21:33

Mithun Rana's user avatar

Mithun RanaMithun Rana

1,2261 gold badge7 silver badges10 bronze badges

1

Switching remote URLs

Open Terminal.

Ist Step:— Change the current working directory to your local project.

2nd Step:— List your existing remotes in order to get the name of the remote you want to change.

git remote -v

origin  https://github.com/USERNAME/REPOSITORY.git (fetch)

origin  https://github.com/USERNAME/REPOSITORY.git (push)

Change your remote’s URL from HTTPS to SSH with the git remote set-url command.

3rd Step:git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

4th Step:— Now Verify that the remote URL has changed.

git remote -v
Verify new remote URL

origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
origin  git@github.com:USERNAME/REPOSITORY.git (push)

Community's user avatar

answered Dec 8, 2017 at 11:01

VIKAS KOHLI's user avatar

VIKAS KOHLIVIKAS KOHLI

7,8763 gold badges49 silver badges57 bronze badges

2

git remote set-url origin git://new.location

(alternatively, open .git/config, look for [remote "origin"], and edit the url = line.

You can check it worked by examining the remotes:

git remote -v
# origin  git://new.location (fetch)
# origin  git://new.location (push)

Next time you push, you’ll have to specify the new upstream branch, e.g.:

git push -u origin master

See also: GitHub: Changing a remote’s URL

answered Apr 26, 2015 at 23:13

Zaz's user avatar

ZazZaz

45.4k11 gold badges82 silver badges97 bronze badges

2

As seen here,

$ git remote rm origin
$ git remote add origin git@github.com:aplikacjainfo/proj1.git
$ git config master.remote origin
$ git config master.merge refs/heads/master

trashgod's user avatar

trashgod

203k29 gold badges242 silver badges1028 bronze badges

answered Apr 2, 2020 at 8:24

Zahid Hassan Shaikot's user avatar

3

  1. remove origin using command on gitbash
    git remote rm origin
  2. And now add new Origin using gitbash
    git remote add origin (Copy HTTP URL from your project repository in bit bucket)
    done

answered Jun 24, 2016 at 11:10

Sunil Chaudhary's user avatar

3

First you need to type this command to view existing remotes

git remote -v

Then second you need to type this command to Change the ‘origin’ remote’s URL

git remote set-url origin <paste your GitHub URL>

arnavakhoury's user avatar

answered May 1, 2022 at 23:05

Abdullah Al Mahmud's user avatar

Write the below command from your repo terminal:

git remote set-url origin git@github.com:<username>/<repo>.git

Refer this link for more details about changing the url in the remote.

answered Dec 19, 2019 at 9:25

viveknaskar's user avatar

viveknaskarviveknaskar

2,0161 gold badge19 silver badges34 bronze badges

0

To check git remote connection:

git remote -v

Now, set the local repository to remote git:

git remote set-url origin https://NewRepoLink.git

Now to make it upstream or push use following code:

git push --set-upstream origin master -f

answered Dec 18, 2018 at 5:22

Anupam Maurya's user avatar

1

Navigate to the project root of the local repository and check for existing remotes:

git remote -v

If your repository is using SSH you will see something like:

> origin  git@github.com:USERNAME/REPOSITORY.git (fetch)
> origin  git@github.com:USERNAME/REPOSITORY.git (push)

And if your repository is using HTTPS you will see something like:

> origin  https://github.com/USERNAME/REPOSITORY.git (fetch)
> origin  https://github.com/USERNAME/REPOSITORY.git (push)

Changing the URL is done with git remote set-url. Depending on the output of git remote -v, you can change the URL in the following manner:

In case of SSH, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin git@github.com:USERNAME/NEW_REPOSITORY.git

And in case of HTTPS, you can change the URL from REPOSITORY.git to NEW_REPOSITORY.git like:

$ git remote set-url origin https://github.com/USERNAME/NEW_REPOSITORY.git

NOTE: If you’ve changed your GitHub username, you can follow the same process as above to update the change in the username associated with your repository. You would only have to update the USERNAME in the git remote set-url command.

answered Aug 17, 2020 at 20:03

Saurabh's user avatar

SaurabhSaurabh

4,0962 gold badges28 silver badges39 bronze badges

if you cloned your local will automatically consist,

remote URL where it gets cloned.

you can check it using git remote -v

if you want to made change in it,

git remote set-url origin https://github.io/my_repo.git

here,

origin — your branch

if you want to overwrite existing branch you can still use it.. it will override your existing … it will do,

git remote remove url
and 
git remote add origin url

for you…

answered Jul 31, 2017 at 7:33

Mohideen bin Mohammed's user avatar

1

I worked:

git remote set-url origin <project>

answered May 6, 2018 at 18:24

Diego Santa Cruz Mendezú's user avatar

In the Git Bash, enter the command:

git remote set-url origin https://NewRepoLink.git

Enter the Credentials

Done

answered Apr 25, 2017 at 9:48

devDeejay's user avatar

devDeejaydevDeejay

5,3551 gold badge26 silver badges38 bronze badges

You have a lot of ways to do that:

Console

git remote set-url origin [Here new url] 

Just be sure that you’ve opened it in a place where a repository is.

Config

It is placed in .git/config (same folder as repository)

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = [Here new url]  <------------------------------------
...

TortoiseGit

Step 1 - open settings

Step 2 - change url

Then just edit URL.

SourceTree

  1. Click on the «Settings» button on the toolbar to open the Repository Settings window.

  2. Click «Add» to add a remote repository path to the repository. A «Remote details» window will open.

  3. Enter a name for the remote path.

  4. Enter the URL/Path for the remote repository

  5. Enter the username for the hosting service for the remote repository.

  6. Click ‘OK’ to add the remote path.

  7. Back on the Repository Settings window, click ‘OK’. The new remote path should be added on the repository now.

  8. If you need to edit an already added remote path, just click the ‘Edit’ button. You should be directed to the «Remote details» window where you can edit the details (URL/Path/Host Type) of the remote path.

  9. To remove a remote repository path, click the ‘Remove’ button

enter image description here

enter image description here

ref. Support

answered Apr 2, 2019 at 13:37

Przemek Struciński's user avatar

For me, the accepted answer worked only in the case of fetch but not pull. I did the following to make it work for push as well.

git remote set-url --push origin new.git.url/here

So to update the fetch URL:

git remote set-url origin new.git.url/here

To update the pull URL:

git remote set-url --push origin new.git.url/here

answered May 6, 2021 at 11:27

Shailendra Madda's user avatar

Shailendra MaddaShailendra Madda

20.1k15 gold badges95 silver badges137 bronze badges

Change remote git URI to git@github.com rather than https://github.com

git remote set-url origin git@github.com:<username>/<repo>.git

Example:

git remote set-url origin git@github.com:Chetabahana/my_repo_name.git

The benefit is that you may do git push automatically when you use ssh-agent :

#!/bin/bash

# Check ssh connection
ssh-add -l &>/dev/null
[[ "$?" == 2 ]] && eval `ssh-agent`
ssh-add -l &>/dev/null
[[ "$?" == 1 ]] && expect $HOME/.ssh/agent

# Send git commands to push
git add . && git commit -m "your commit" && git push -u origin master

Put a script file $HOME/.ssh/agent to let it runs ssh-add using expect as below:

#!/usr/bin/expect -f
set HOME $env(HOME)
spawn ssh-add $HOME/.ssh/id_rsa
expect "Enter passphrase for $HOME/.ssh/id_rsa:"
send "<my_passphrase>n";
expect "Identity added: $HOME/.ssh/id_rsa ($HOME/.ssh/id_rsa)"
interact

BenKoshy's user avatar

BenKoshy

32k14 gold badges103 silver badges78 bronze badges

answered May 25, 2019 at 11:54

eQ19's user avatar

eQ19eQ19

9,5303 gold badges62 silver badges76 bronze badges

To change the remote upstream:
git remote set-url origin <url>


To add more upstreams:
git remote add newplace <url>

So you can choose where to work
git push origin <branch> or git push newplace <branch>

answered Feb 28, 2020 at 13:43

Anderson Cossul's user avatar

0

You can change the url by editing the config file.
Go to your project root:

nano .git/config

Then edit the url field and set your new url.
Save the changes. You can verify the changes by using the command.

git remote -v 

answered Feb 7, 2020 at 4:24

Abhi Das's user avatar

Abhi DasAbhi Das

50110 silver badges11 bronze badges

An alternative approach is to rename the ‘old’ origin (in the example below I name it simply old-origin) and adding a new one. This might be the desired approach if you still want to be able to push to the old origin every now and then:

git remote rename origin old-origin
git remote add origin git@new-git-server.com>:<username>/<projectname>.git

And in case you need to push your local state to the new origin:

git push -u origin --all
git push -u origin --tags

answered Sep 20, 2020 at 12:25

j-i-l's user avatar

j-i-lj-i-l

9,7862 gold badges49 silver badges69 bronze badges

If you’re using TortoiseGit then follow the below steps:

  1. Go to your local checkout folder and right click to go to TortoiseGit -> Settings
  2. In the left pane choose Git -> Remote
  3. In the right pane choose origin
  4. Now change the URL text box value to where ever your new remote repository is

Your branch and all your local commits will remain intact and you can keep working as you were before.

Don't Panic's user avatar

Don’t Panic

40.8k10 gold badges61 silver badges78 bronze badges

answered Aug 20, 2017 at 15:14

Vipul bhojwani's user avatar

0

It will work fine, you can try this

For SSH:

command: git remote set-url origin <ssh_url>

example: git remote set-url origin git@github.com:username/rep_name.git

For HTTPS:

command: git remote set-url origin <https_url>

example: git remote set-url origin https://github.com/username/REPOSITORY.git

answered Dec 26, 2022 at 7:51

MD. SHIFULLAH's user avatar

Removing a remote

Use the git remote rm command to remove a remote URL from your repository.

    $ git remote -v
    # View current remotes
    > origin  https://github.com/OWNER/REPOSITORY.git (fetch)
    > origin  https://github.com/OWNER/REPOSITORY.git (push)
    > destination  https://github.com/FORKER/REPOSITORY.git (fetch)
    > destination  https://github.com/FORKER/REPOSITORY.git (push)

    $ git remote rm destination
    # Remove remote
    $ git remote -v
    # Verify it's gone
    > origin  https://github.com/OWNER/REPOSITORY.git (fetch)
    > origin  https://github.com/OWNER/REPOSITORY.git (push)

answered Jun 6, 2020 at 11:05

Tayyab Roy's user avatar

Tayyab RoyTayyab Roy

4235 silver badges7 bronze badges

If you would like to set the username and password as well in the origin url, you can follow the below steps.

Exporting the password in a variable would avoid issues with special characters.

Steps:

export gituser='<Username>:<password>@'
git remote set-url origin https://${gituser}<gitlab_repo_url> 
git push origin <Branch Name>

answered Mar 3, 2021 at 5:52

Rajesh Somasundaram's user avatar

check your privilege

in my case i need to check my username

i have two or three repository with seperate credentials.

problem is my permission i have two private git server and repositories

this second account is admin of that new repo and first one is my default user account and i should grant permission to first

answered Feb 6, 2020 at 16:35

saber tabatabaee yazdi's user avatar

(Only Windows PS) To change a server/protocol recursively in all local repos

Get-ChildItem -Directory -Recurse -Depth [Number] -Hidden -name | %{$_.replace(".git","")} | %{git -C $_ remote set-url origin $(git -C $_ remote get-url origin).replace("[OLD SERVER]", "[NEW SERVER]")}

answered May 17, 2021 at 10:05

bruegth's user avatar

bruegthbruegth

3583 silver badges12 bronze badges

For those who want to make this change from Visual Studio 2019

Open Team Explorer (Ctrl+M)

Home -> Settings

Git -> Repository Settings

Remotes -> Edit

enter image description here

answered Oct 25, 2019 at 17:53

Dinch's user avatar

DinchDinch

5284 silver badges9 bronze badges

With no arguments, shows a list of existing remotes. Several
subcommands are available to perform operations on the remotes.

add

Add a remote named <name> for the repository at
<URL>. The command git fetch <name> can then be used to create and
update remote-tracking branches <name>/<branch>.

With -f option, git fetch <name> is run immediately after
the remote information is set up.

With --tags option, git fetch <name> imports every tag from the
remote repository.

With --no-tags option, git fetch <name> does not import tags from
the remote repository.

By default, only tags on fetched branches are imported
(see git-fetch[1]).

With -t <branch> option, instead of the default glob
refspec for the remote to track all branches under
the refs/remotes/<name>/ namespace, a refspec to track only <branch>
is created. You can give more than one -t <branch> to track
multiple branches without grabbing all branches.

With -m <master> option, a symbolic-ref refs/remotes/<name>/HEAD is set
up to point at remote’s <master> branch. See also the set-head command.

When a fetch mirror is created with --mirror=fetch, the refs will not
be stored in the refs/remotes/ namespace, but rather everything in
refs/ on the remote will be directly mirrored into refs/ in the
local repository. This option only makes sense in bare repositories,
because a fetch would overwrite any local commits.

When a push mirror is created with --mirror=push, then git push
will always behave as if --mirror was passed.

rename

Rename the remote named <old> to <new>. All remote-tracking branches and
configuration settings for the remote are updated.

In case <old> and <new> are the same, and <old> is a file under
$GIT_DIR/remotes or $GIT_DIR/branches, the remote is converted to
the configuration file format.

remove
rm

Remove the remote named <name>. All remote-tracking branches and
configuration settings for the remote are removed.

set-head

Sets or deletes the default branch (i.e. the target of the
symbolic-ref refs/remotes/<name>/HEAD) for
the named remote. Having a default branch for a remote is not required,
but allows the name of the remote to be specified in lieu of a specific
branch. For example, if the default branch for origin is set to
master, then origin may be specified wherever you would normally
specify origin/master.

With -d or --delete, the symbolic ref refs/remotes/<name>/HEAD is deleted.

With -a or --auto, the remote is queried to determine its HEAD, then the
symbolic-ref refs/remotes/<name>/HEAD is set to the same branch. e.g., if the remote
HEAD is pointed at next, git remote set-head origin -a will set
the symbolic-ref refs/remotes/origin/HEAD to refs/remotes/origin/next. This will
only work if refs/remotes/origin/next already exists; if not it must be
fetched first.

Use <branch> to set the symbolic-ref refs/remotes/<name>/HEAD explicitly. e.g., git
remote set-head origin master
will set the symbolic-ref refs/remotes/origin/HEAD to
refs/remotes/origin/master. This will only work if
refs/remotes/origin/master already exists; if not it must be fetched first.

set-branches

Changes the list of branches tracked by the named remote.
This can be used to track a subset of the available remote branches
after the initial setup for a remote.

The named branches will be interpreted as if specified with the
-t option on the git remote add command line.

With --add, instead of replacing the list of currently tracked
branches, adds to that list.

get-url

Retrieves the URLs for a remote. Configurations for insteadOf and
pushInsteadOf are expanded here. By default, only the first URL is listed.

With --push, push URLs are queried rather than fetch URLs.

With --all, all URLs for the remote will be listed.

set-url

Changes URLs for the remote. Sets first URL for remote <name> that matches
regex <oldurl> (first URL if no <oldurl> is given) to <newurl>. If
<oldurl> doesn’t match any URL, an error occurs and nothing is changed.

With --push, push URLs are manipulated instead of fetch URLs.

With --add, instead of changing existing URLs, new URL is added.

With --delete, instead of changing existing URLs, all URLs matching
regex <URL> are deleted for remote <name>. Trying to delete all
non-push URLs is an error.

Note that the push URL and the fetch URL, even though they can
be set differently, must still refer to the same place. What you
pushed to the push URL should be what you would see if you
immediately fetched from the fetch URL. If you are trying to
fetch from one place (e.g. your upstream) and push to another (e.g.
your publishing repository), use two separate remotes.

show

Gives some information about the remote <name>.

With -n option, the remote heads are not queried first with
git ls-remote <name>; cached information is used instead.

prune

Deletes stale references associated with <name>. By default, stale
remote-tracking branches under <name> are deleted, but depending on
global configuration and the configuration of the remote we might even
prune local tags that haven’t been pushed there. Equivalent to git
fetch --prune <name>
, except that no new references will be fetched.

See the PRUNING section of git-fetch[1] for what it’ll prune
depending on various configuration.

With --dry-run option, report what branches would be pruned, but do not
actually prune them.

update

Fetch updates for remotes or remote groups in the repository as defined by
remotes.<group>. If neither group nor remote is specified on the command line,
the configuration parameter remotes.default will be used; if
remotes.default is not defined, all remotes which do not have the
configuration parameter remote.<name>.skipDefaultUpdate set to true will
be updated. (See git-config[1]).

With --prune option, run pruning against all the remotes that are updated.

I’ve recently cloned a repo to my local drive, but now I’m trying to push all changes to a complete new repo. However, git keeps telling me that permission is denied, and that’s because it’s trying to push to the originally-cloned repo.

DETAILS:

I originally cloned from https://github.com/taylonr/intro-to-protractor (i.e. based on a Pluralsight course at https://app.pluralsight.com/library/courses/protractor-introduction/table-of-contents ) .

Now that I’ve completed the course, I’d like to push my finalized code up to my own git repo (which I just created on github):

https://github.com/robertmazzo/intro-to-protractor

When I use the following git command:

git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

it tells me remote origin already exists , which I guess is fine because I already created it on github.com.

However, when I push my changes up I’m getting an exception.

git push origin master

remote: Permission to taylonr/intro-to-protractor.git denied to robertmazzo.
fatal: unable to access 'https://github.com/taylonr/intro-to-protractor.git/':
The requested URL returned error: 403

So I’m investigating how I can switch to my new repository, but this is exactly where my issue is. I cannot figure this part out.

user229044's user avatar

user229044

229k40 gold badges329 silver badges336 bronze badges

asked Sep 6, 2016 at 14:31

bob.mazzo's user avatar

1

Before you can add a new remote named «origin», you need to either delete the old one, or simply rename it if you still need access to it for some reason.

# Pick one
git remote remove origin            # delete it, or ...
git remote rename origin old-origin # ... rename it

# Now you can add the new one
git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

answered Sep 6, 2016 at 14:34

chepner's user avatar

chepnerchepner

478k70 gold badges502 silver badges653 bronze badges

origin is only an alias to identify your remote repository.

You can create a new remote reference and push

git remote add new_origin https://github.com/robertmazzo/intro-to-protractor.git
git push new_origin master

If you want to remove the previous reference

git remote remove origin

answered Sep 6, 2016 at 14:34

lubilis's user avatar

lubilislubilis

3,8424 gold badges32 silver badges54 bronze badges

Either add a new remote

git remote add <name> <url>

or, if you completely want to remove the old origin, first do

git remote remove origin

and then

git remote add origin <url>

Note that the message remote origin already exists is not fine. It tells you that the operation failed, i.e. it could not set the new remote.

answered Sep 6, 2016 at 14:33

Martin Nyolt's user avatar

Martin NyoltMartin Nyolt

4,3043 gold badges26 silver badges35 bronze badges

I’ve recently cloned a repo to my local drive, but now I’m trying to push all changes to a complete new repo. However, git keeps telling me that permission is denied, and that’s because it’s trying to push to the originally-cloned repo.

DETAILS:

I originally cloned from https://github.com/taylonr/intro-to-protractor (i.e. based on a Pluralsight course at https://app.pluralsight.com/library/courses/protractor-introduction/table-of-contents ) .

Now that I’ve completed the course, I’d like to push my finalized code up to my own git repo (which I just created on github):

https://github.com/robertmazzo/intro-to-protractor

When I use the following git command:

git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

it tells me remote origin already exists , which I guess is fine because I already created it on github.com.

However, when I push my changes up I’m getting an exception.

git push origin master

remote: Permission to taylonr/intro-to-protractor.git denied to robertmazzo.
fatal: unable to access 'https://github.com/taylonr/intro-to-protractor.git/':
The requested URL returned error: 403

So I’m investigating how I can switch to my new repository, but this is exactly where my issue is. I cannot figure this part out.

user229044's user avatar

user229044

229k40 gold badges329 silver badges336 bronze badges

asked Sep 6, 2016 at 14:31

bob.mazzo's user avatar

1

Before you can add a new remote named «origin», you need to either delete the old one, or simply rename it if you still need access to it for some reason.

# Pick one
git remote remove origin            # delete it, or ...
git remote rename origin old-origin # ... rename it

# Now you can add the new one
git remote add origin https://github.com/robertmazzo/intro-to-protractor.git

answered Sep 6, 2016 at 14:34

chepner's user avatar

chepnerchepner

478k70 gold badges502 silver badges653 bronze badges

origin is only an alias to identify your remote repository.

You can create a new remote reference and push

git remote add new_origin https://github.com/robertmazzo/intro-to-protractor.git
git push new_origin master

If you want to remove the previous reference

git remote remove origin

answered Sep 6, 2016 at 14:34

lubilis's user avatar

lubilislubilis

3,8424 gold badges32 silver badges54 bronze badges

Either add a new remote

git remote add <name> <url>

or, if you completely want to remove the old origin, first do

git remote remove origin

and then

git remote add origin <url>

Note that the message remote origin already exists is not fine. It tells you that the operation failed, i.e. it could not set the new remote.

answered Sep 6, 2016 at 14:33

Martin Nyolt's user avatar

Martin NyoltMartin Nyolt

4,3043 gold badges26 silver badges35 bronze badges

Продолжаю изучение темы Git и GitHub. На повестке дня стоит вопрос — каким образом можно изменить ссылку существующего репозитория?

Нет — не так! Попробую зайти с другой стороны и сказать иначе. Имеется готовый репозиторий Template, размещенный на сервере GitHub. Этот репозиторий является шаблоном (template starter) при создании разнообразных проектов. Нечто похожим на известный HTML5 Boilerplate.

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

$ git clone https://github.com/gearmobile/template.git project

Затем в созданном репозитории Project разрабатывается требуемый проект.

Но есть одно НО — необходимо преобразовать видоизмененный репозиторий Project в отдельный, самостоятельный репозиторий. Конечно, по большому счету, это уже и есть отдельный, самостоятельный репозиторий.

Но вот ссылка у репозитория Project указывает на оригинал — репозиторий Template. И если произвести

на GitHub, то произойдет обновление репозитория Template.

А этого крайне нежелательно допустить, так как этот репозиторий является стартовым, чистым листом для всех новых проектов!

У меня же стоит такая задача — скопировать стартовый репозиторий Template на локальную машину, преобразовать его в конкретный проект, вновь залить на GitHub уже как самостоятельный репозиторий с именем проекта в качестве имени репозитория. Как поступить?

Можно решить вопрос несколькими способами. Ниже приведу пару из них — самых простых и доступных для моего понимания вечного newbie в GitGitHub. Может быть, по мере освоения темы дополню статью более универсальным и грамотным способом.

Правка config

У клонированного на локальную машину репозитория ссылка на его удаленный оригинал размещена в конфигурационном файле

по пути

1
.git/config

, в секции

1
[remote "origin"]

, в переменной с именем

1
url

:

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/template.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Поэтому в локальном репозитории Project можно просто изменить эту ссылку с помощью любого текстового редактора.

Отредактирую файл

и изменю в нем ссылку с

https://github.com/gearmobile/template.git

на

https://github.com/gearmobile/project.git

… где последняя — это ссылка на новый пустой репозиторий Project, который я создал на GitHub.

Теперь конфигурационный файл

для локального репозитория Project будет выглядеть таким образом (обратить внимание на переменную

1
url

):

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/project.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Все — теперь локальный репозиторий Project является абсолютно самостоятельным и уникальным репозиторием, связанным ссылкой со своей удаленной копией на сервере GitHub.

Осталось только сделать

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

1
-f

(как это описано в предыдущей статье Откат коммитов на GitHub):

$ git push -f

Команда set-url

Второй способ практически идентичен предыдущему за тем лишь исключением, что он более правильный, так как для изменения url-адреса репозитория используется предназначенная для этого консольная команда Git —

.

Точно также создаю на локальной машине копию Another Project удаленного репозитория Template:

$ git clone https://github.com/gearmobile/template.git another-project

Ссылка в новом репозитории Another-Project все также указывает на свой оригинал — репозиторий Template:

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/template.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Создаю на GitHub новый репозиторий Another-Project, который будет удаленной копией локального (уже существующего) репозитория Another-Project. И изменяю ссылку на вновь созданный удаленный репозиторий Another-Project:

$ git remote set-url origin https://github.com/gearmobile/another-project.git

Проверяю, изменилась ли ссылка в конфигурационном файле

(переменная

1
url

):

$ cat .git/config

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
  ignorecase = true
  precomposeunicode = true

[remote "origin"]
  url = https://github.com/gearmobile/another-project.git
  fetch = +refs/heads/*:refs/remotes/origin/*

[branch "master"]
  remote = origin
  merge = refs/heads/master

Да, ссылка была успешно изменена на новый удаленный репозиторий Another-Project. Можно вносить изменения и выполнять

на GitHub.

Небольшое заключение

Преимущество двух описанных выше способ в том, что не теряется история коммитов.

На этом пока все.


Git remote — это указатель, который ссылается на другую копию репозитория, которая обычно размещается на удаленном сервере.

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

В этом руководстве объясняется, как изменить URL-адрес удаленного Git.

Изменение URL-адреса Git Remote

Каждый репозиторий Git может иметь ноль или более связанных с ним пультов Git. Когда вы клонируете репозиторий, имя пульта дистанционного управления автоматически устанавливается на origin и указывает на репозиторий, из которого вы клонировали. Если вы создали репозиторий локально, вы можете добавить новый пульт .

Пульт дистанционного управления может указывать на репозиторий, размещенный в службе хостинга Git, такой как GitHub, GitLab и BitBucket, или на ваш частный сервер Git .

Выполните следующие действия, чтобы изменить URL-адрес пульта дистанционного управления:

  1. Перейдите в каталог, в котором находится репозиторий:

     cd /path/to/repository
  2. Запустите git remote чтобы git remote список существующих пультов и просмотреть их имена и URL-адреса:

     git remote -v

    Результат будет выглядеть примерно так:

     origin https://github.com/user/repo_name.git (fetch) origin https://github.com/user/repo_name.git (push)
  3. Используйте команду git remote set-url за которой следует удаленное имя и удаленный URL-адрес:

     git remote set-url <remote-name> <remote-url>

    URL-адрес удаленного устройства может начинаться с HTTPS или SSH, в зависимости от используемого протокола. Если протокол не указан, по умолчанию используется SSH. URL-адрес можно найти на странице репозитория вашей службы хостинга Git.

    Если вы переходите на HTTPS, URL-адрес будет выглядеть примерно так:

     https://gitserver.com/user/repo_name.git

    Если вы переходите на SSH, URL-адрес будет выглядеть так:

    Например, чтобы изменить URL-адрес origin на [email protected]:user/repo_name.git , введите:

     git remote set-url origin [email protected]:user/repo_name.git
  4. Убедитесь, что URL-адрес удаленного устройства был успешно изменен, перечислив удаленные подключения:

     git remote -v

    Результат должен выглядеть так:

     origin ssh://[email protected]:user/repo_name.git (fetch) origin ssh://[email protected]:user/repo_name.git (push)

Вот и все. Вы успешно изменили URL-адрес пульта дистанционного управления.

Команда git remote set-url обновляет файл .git/config репозитория с новым URL-адресом удаленного репозитория.

.git/config

...

[remote "origin"]
        url = [email protected]:user/repo_name.git
        fetch = +refs/heads/*:refs/remotes/origin/*

Вы также можете изменить URL-адрес пульта дистанционного управления, отредактировав файл .git/config в текстовом редакторе . Однако рекомендуется использовать команду git.

Выводы

Изменить URL-адрес удаленного Git так же просто, как запустить: git remote set-url <remote-name> <remote-url> .

Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.

Понравилась статья? Поделить с друзьями:
  • Как изменить patchwall
  • Как изменить readme github
  • Как изменить rdpwrap ini
  • Как изменить rdp файл через блокнот
  • Как изменить rcon пароль