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
orupstream
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
- If you’re updating to use HTTPS, your URL might look like:
Switching remote URLs from SSH to HTTPS
- Open TerminalTerminalGit Bash.
- Change the current working directory to your local project.
- 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)
- 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
- 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
- Open TerminalTerminalGit Bash.
- Change the current working directory to your local project.
- 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.$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
- 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.)
answered Mar 12, 2010 at 12:55
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
answered Oct 10, 2013 at 14:43
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
answered Dec 28, 2015 at 4:53
최봉재최봉재
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
40.9k28 gold badges126 silver badges179 bronze badges
answered Feb 15, 2011 at 2:52
yodayoda
4,7593 gold badges19 silver badges9 bronze badges
2
This is very easy and simple; just follow these instructions.
- For adding or changing the remote origin:
git remote set-url origin githubrepurl
- To see which remote URL you have currently in this local repository:
git remote show origin
answered Feb 1, 2022 at 21:33
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)
answered Dec 8, 2017 at 11:01
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
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
203k29 gold badges242 silver badges1028 bronze badges
answered Apr 2, 2020 at 8:24
3
- remove origin using command on gitbash
git remote rm origin - 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
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>
answered May 1, 2022 at 23:05
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
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
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
SaurabhSaurabh
4,0862 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
1
I worked:
git remote set-url origin <project>
answered May 6, 2018 at 18:24
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
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
Then just edit URL.
SourceTree
-
Click on the «Settings» button on the toolbar to open the Repository Settings window.
-
Click «Add» to add a remote repository path to the repository. A «Remote details» window will open.
-
Enter a name for the remote path.
-
Enter the URL/Path for the remote repository
-
Enter the username for the hosting service for the remote repository.
-
Click ‘OK’ to add the remote path.
-
Back on the Repository Settings window, click ‘OK’. The new remote path should be added on the repository now.
-
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.
-
To remove a remote repository path, click the ‘Remove’ button
ref. Support
answered Apr 2, 2019 at 13:37
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 MaddaShailendra Madda
20.1k15 gold badges95 silver badges137 bronze badges
Change remote git URI to
git@github.com
rather thanhttps://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
32k14 gold badges103 silver badges78 bronze badges
answered May 25, 2019 at 11:54
eQ19eQ19
9,5203 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
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 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-lj-i-l
9,7862 gold badges49 silver badges69 bronze badges
If you’re using TortoiseGit then follow the below steps:
- Go to your local checkout folder and right click to go to
TortoiseGit -> Settings
- In the left pane choose
Git -> Remote
- In the right pane choose
origin
- 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
40.8k10 gold badges61 silver badges78 bronze badges
answered Aug 20, 2017 at 15:14
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
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 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
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
(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
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
answered Oct 25, 2019 at 17:53
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 commandgit 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
therefs/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-refrefs/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
, thengit 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-refrefs/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 fororigin
is set to
master
, thenorigin
may be specified wherever you would normally
specifyorigin/master
.With
-d
or--delete
, the symbolic refrefs/remotes/<name>/HEAD
is deleted.With
-a
or--auto
, the remote is queried to determine itsHEAD
, then the
symbolic-refrefs/remotes/<name>/HEAD
is set to the same branch. e.g., if the remote
HEAD
is pointed atnext
,git remote set-head origin -a
will set
the symbolic-refrefs/remotes/origin/HEAD
torefs/remotes/origin/next
. This will
only work ifrefs/remotes/origin/next
already exists; if not it must be
fetched first.Use
<branch>
to set the symbolic-refrefs/remotes/<name>/HEAD
explicitly. e.g.,git
will set the symbolic-ref
remote set-head origin masterrefs/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 thegit 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 togit
, except that no new references will be fetched.
fetch --prune <name>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 parameterremote.<name>.skipDefaultUpdate
set to true will
be updated. (See git-config[1]).With
--prune
option, run pruning against all the remotes that are updated.
Продолжаю изучение темы 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-адрес пульта дистанционного управления:
-
Перейдите в каталог, в котором находится репозиторий:
cd /path/to/repository
-
Запустите
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)
-
Используйте команду
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
-
Убедитесь, что 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>
.
Если вы столкнулись с проблемой или хотите оставить отзыв, оставьте комментарий ниже.
Using git remote set-url to change remote repository URL
It is inevitable to push changes that you make in your local project upstream while using git. In the process, you may require to use the git remote set-url
function if you want to push the changes to a different URL. This could be because you changed your user name or you want to move the project to a new repository. Git has provided reliable means to run such operations without affecting the project progress or the work of other collaborators.
In this tutorial, we will practice how to change a remote URL without running an error supported by examples.
git remote set-url syntax
Following is a basic syntax which we will use through out this article to change remote URL. For complete list of supported options you can check official git documentation.
git remote set-url [--push] <name> <newurl> [<oldurl>]
git remote set-url --add [--push] <name> <newurl>
git remote set-url --delete [--push] <name> <url>
ALSO READ: git stash explained in detail with examples
Git workflow to change remote URL
Following are the brief steps required to change a remote URL properly in git
git remote -v # View the existing remotes # origin https://github.com/user/repo-1.git (fetch) # origin https://github.com/user/repo-1.git (push) git remote set-url origin https://github.com/user/repo-2.git # Change the 'origin' remote's URL git remote -v # Verify the new remote URL # origin https://github.com/user/repo-2.git (fetch) # origin https://github.com/user/repo-2.git (push)
Setting up the lab environment
Before we can practice using the git remote set-url
command, we shall first prepare our lab environment. We will clone a remote project git-url
to our local work station windows 10 pro. We will also be using git version 2.32.0.windows.2 to run this experiment.
Below is the sample output for the git clone command.
$ git clone https://github.com/Maureen-M/git-url.git
Cloning into 'git-url'...
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Receiving objects: 100% (3/3), done.
How to change remote URL to repo with new account user name
Let’s assume we had issues with the current git account and had to change the user name from Maureen-M
to Josephine-M-Tech
after cloning. Such a change will affect the process of pushing your commits upstream. Your local changes will still be using your old username and will require you to update the changes to the new user name.
ALSO READ: git push force Explained [With Examples]
It is such a scenario that will prompt you to use the git remote set url
command. Let put that into practice as follows:
Using the active project git-url
we shall run a few commits and try to push the changes upstream to see what happens.
To view the current remote URLs before changing the git account username we shall run the git remote –v
command as shown below:
$ git remote -v
origin https://github.com/Maureen-M/git-url.git (fetch)
origin https://github.com/Maureen-M/git-url.git (push)
Now let’s add a few commits to the local project git-url
before pushing upstream
$ git checkout -b newbranch Switched to a new branch 'newbranch' $ touch newfile.css $ git add . $ git commit -m "newfile.css" [newbranch 0d78950] newfile.css 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 newfile.css $ git push --set-upstream origin newbranch Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 4 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 272 bytes | 272.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), completed with 1 local object. remote: This repository moved. Please use the new location: remote: https://github.com/Josephine-Techie/git-trial.git remote: remote: Create a pull request for 'newbranch' on GitHub by visiting: remote: https://github.com/Josephine-Techie/git-trial/pull/new/newbranch remote: To https://github.com/Maureen-M/git-trial.git * [new branch] newbranch -> newbranch Branch 'newbranch' set up to track remote branch 'newbranch' from 'origin'.
Note the message where git informs you that the repository moved and you will have to use the new location.
ALSO READ: git push explained with practical examples [Beginners]
We will now apply the $ git remote set-url <remote_name> <remote_url>
command to update the changes to the new location as follows:
$ git remote set-url origin https://github.com/Josephine-Techie/git-trial.git
To view the set remote URL we shall run git remote –v
command again:
$ git remote -v
origin github.com:Josephine-M-Tech/git-url.git (fetch)
origin github.com:Josephine-M-Tech/git-url.git (push)
It’s a success! We now have a new remote URL set using the git remote set-url
command.
Understand that git can automatically update the new changes by linking the two URLs which you can still work with. An issue may however arise if the old username URL is taken by someone else and the link becomes broken.
To view the set URL in action, let’s make changes to the committed file and push upstream using the active branch newbranch
as follows:
$ git commit -m "edited newfile.css" [newbranch 14fc920] edited newfile.css 1 file changed, 1 insertion(+) $ git push origin newbranch Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 4 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), completed with 1 local object. To https://github.com/Josephine-Techie/git-trial.git 0d78950..14fc920 newbranch -> newbranch
You notice the new push action no longer has a warning message about the change in URL as it has been updated.
ALSO READ: git revert to previous commit [Practical Examples]
How to add a remote URL from the local repository
To set a remote URL from a local repository use the git remote add <remote-name> <remote-url>
command as demonstrated below:
We will use the master
branch in the git-url
project for this example.
$ git checkout master
Switched to branch 'master'
Your branch is up to date with 'origin/master'.
Next, we shall run git remote –v
command to view all the present remote as shown below:
$ git remote -v
origin https://github.com/Josephine-Techie/git-trial.git (fetch)
origin https://github.com/Josephine-Techie/git-trial.git (push)
To set another remote from the local repository we shall run the following:
$ git remote add new-user-name https://github.com/Josephine-M-Tech/git-url.git
We have now set a new remote url new-username
in our remote repository git-url
.
We shall run the git remote –v
command to view all the remotes URLs available as shown below:
new-username https://github.com/Josephine-Techie/git-trial.git (fetch) new-username https://github.com/Josephine-Techie/git-trial.git (push) origin https://github.com/Josephine-Techie/git-trial.git (fetch) origin https://github.com/Josephine-Techie/git-trial.git (push)
The remote new-username
url has been added.
How to push new commits upstream using git remote set URL
To understand how to push commits into the set remote URL new-user
we shall commit some changes to the active branch master as follows;
$ touch new-2.txt
$ git add .
$ git commit -m "new-2.txt"
[master f74febb] new-2.txt
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 new-2.txt
Now, we shall push the changes upstream using the git remote set-url --add --push origin
command as illustrated below:
$ git remote set-url --add --push origin new-user/git-url.git
Next, we will run the git status
function to confirm if the changes were successfully pushed upstream.
$ git status
On branch master
nothing to commit, working tree clean
The status confirms a clean working tree and therefore the push procedure was a success.
ALSO READ: Git command Cheat Sheet [One STOP Solution]
Note that the git remote set-url --add --push origin
function, when used, it will override any push made from the default url
How to delete a remote URL in git
To remove a remote URL you will use the git remote remove <name>
command. In this example, we are going to remove the new-user URL
as follows;
Let’s view the current URLs as shown:
new-user https://github.com/Josephine-M-Tech/git-url.git (fetch)
new-user https://github.com/Josephine-M-Tech/git-url.git (push)
new-username https://github.com/Josephine-Techie/git-trial.git (fetch)
new-username https://github.com/Josephine-Techie/git-trial.git (push)
$ git remote remove new-user
We will then run the git remote –v
command to confirm the removal of new-user as demonstrated below:
$ git remote -v new-username https://github.com/Josephine-Techie/git-trial.git (fetch) new-username https://github.com/Josephine-Techie/git-trial.git (push)
From the output, we no longer have the new-user URL
among the list of remote URLs.
How to set a remote SSH URL in git
To set a remote URL if you have SSH configured GitHub a count follows the same process as changing the remote URL. You will insert the new SSH-remote-url in place of the new-remote-url as shown in the syntax below.
$ git remote set-url <remote_name> <ssh_remote_url>
Here is an example of how the SSH URL looks like:
git@github.com:Josephine-Techie/git-url.git
Now we shall use in the $ git remote set-url <remote_name> <ssh_remote_url>
command to set a new URL as shown below:
$ git remote set-url origin git@github.com:Josephine-Techie/git-url.git
$ git remote -v
new-user https://github.com/Josephine-M-Tech/git-url.git (fetch)
new-user https://github.com/Josephine-M-Tech/git-url.git (push)
new-username https://github.com/Josephine-Techie/git-trial.git (fetch)
new-username https://github.com/Josephine-Techie/git-trial.git (push)
origin git@github.com:Josephine-Techie/git-url.git (fetch)
origin git@github.com:Josephine-Techie/git-url.git (push)
We have set a new URL origin
using git SSH URL
ALSO READ: SOLVED: git remove file from tracking [Practical Examples]
Summary
We have covered the following topics relating to git remote set URL:
- Understanding git remote set URL
- How to set remote URL in git scenarios
- How to change remote repository URL
- How to push new commits upstream using git remote set URL function
- How to delete a remote URL
- How to set a remote SSH in git
Further Reading
Git-remote-set-url
In this article we’ll follow simple steps to change a remote Git repository using the command line.
- List your existing remotes
- Change a remote Git repository
1. List your existing remotes
To list the existing remotes we open the terminal and type in the following command:
$ git remote -v
If you copied the link to the repository from Clone with SSH in your GitLab, the output should look something like this:
origin This email address is being protected from spambots. You need JavaScript enabled to view it.:user/repository.git (fetch)
origin This email address is being protected from spambots. You need JavaScript enabled to view it.:user/repository.git (push)
If you copied the link to the repository from Clone with HTTPS in your GitLab, the output should look something like this:
origin https://your.git.repo.example.com/user/repository.git (fetch)
origin https://your.git.repo.example.com/user/repository.git (push)
Note: To find the SSH and HTTPS URLs, go to your GitLab, select your project, and click on Clone.
We can change the remote repository by using git remote set-url command:
$ git remote set-url origin This email address is being protected from spambots. You need JavaScript enabled to view it.:user/repository2.git
The command takes two arguments: existing name of the remote (in our case origin) and a new remote URL (in our case This email address is being protected from spambots. You need JavaScript enabled to view it.:user/repository2.git)
In case you change your remote repository to https URL, you will be prompted for your username and password next time you use git fetch, git pull or git push.
If you try to use a link to a non-existing remote, you will get the following error:
> fatal: No such remote 'origin'
When this happens, recheck your URL and make sure it matches the one in your GitLab or GitHub.
If you’d like to learn about Git make sure to check the following articles:
- Push identical code into two git remote repositories
- How to git revert a commit
I created a local GIT repository on Windows. Let’s call it AAA. I staged, committed, and pushed the contents to GitHub. git@github.com:username/AAA.git
I realized I made a mistake with the name.
On GitHub, I renamed it to git@github.com:username/BBB.git
Now, on my Windows machine, I need to change git@github.com:username/AAA.git
to git@github.com:username/BBB.git
because the settings are still trying to «push» to git@github.com:username/AAA.git
but I need to push to git@github.com:username/BBB.git
now.
How could I do that?
asked Nov 26, 2009 at 0:14
0
git remote set-url origin <URL>
animuson♦
53.2k28 gold badges142 silver badges147 bronze badges
answered Dec 30, 2011 at 5:47
hallucinationshallucinations
3,3942 gold badges15 silver badges23 bronze badges
3
The easiest way to tweak this in my opinion (imho) is to edit the .git/config file in your repository. Look for the entry you messed up and just tweak the URL.
On my machine in a repo I regularly use it looks like this:
KidA% cat .git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
autocflg = true
[remote "origin"]
url = ssh://localhost:8888/opt/local/var/git/project.git
#url = ssh://xxx.xxx.xxx.xxx:80/opt/local/var/git/project.git
fetch = +refs/heads/*:refs/remotes/origin/*
The line you see commented out is an alternative address for the repository that I sometimes switch to simply by changing which line is commented out.
This is the file that is getting manipulated under-the-hood when you run something like git remote rm
or git remote add
but in this case since its only a typo you made it might make sense to correct it this way.
wonea
4,63317 gold badges84 silver badges138 bronze badges
answered Nov 26, 2009 at 0:58
jkpjkp
77.4k28 gold badges102 silver badges103 bronze badges
One more way to do this is:
git config remote.origin.url https://github.com/abc/abc.git
To see the existing URL just do:
git config remote.origin.url
Jian
9,7327 gold badges37 silver badges42 bronze badges
answered Apr 3, 2013 at 10:28
Take a look in .git/config and make the changes you need.
Alternatively you could use
git remote rm [name of the url you sets on adding]
and
git remote add [name] [URL]
Or just
git remote set-url [URL]
Before you do anything wrong, double check with
git help remote
AsimRazaKhan
2,0953 gold badges20 silver badges36 bronze badges
answered Nov 26, 2009 at 0:32
SteinbitglisSteinbitglis
2,4422 gold badges26 silver badges39 bronze badges
0