git - remote add origin vs remote set-url origin

I create a new repository:

git init
echo "# MESSAGE" >> README.md
git add README.md
git commit -m "first commit"

Then I want to push my commit to the empty remote repository created on github so I have to set remote.

What is difference between using following commands ? :

git remote add origin [email protected]:User/UserRepo.git
git remote set-url origin [email protected]:User/UserRepo.git

At the end I perform push:

git push -u origin master

What happens when I call git remote set-url origin just after git init? Does git remote set-url origin create origin? If origin already exists after git init there is no difference between using those commands in my scenario, right?


Solution 1:

below is used to a add a new remote:

git remote add origin [email protected]:User/UserRepo.git

below is used to change the url of an existing remote repository:

git remote set-url origin [email protected]:User/UserRepo.git

below will push your code to the master branch of the remote repository defined with origin and -u let you point your current local branch to the remote master branch:

git push -u origin master

Documentation

Solution 2:

Below will reinitialize your local repo; also clearing remote repos (ie origin):

git init

Then below, will create 'origin' if it doesn't exist:

git remote add origin [repo-url]

Else, you can use the set-url subcommand to edit an existing remote:

git remote set-url origin [repo-url]

Also, you can check existing remotes with

git remote -v

Hope this helps!