How do I push a new local branch to a remote Git repository and track it too?

To push a new local branch to a remote Git repository and set up tracking (so git pull/git push work without extra arguments), use the following command:

git push -u origin <branch-name>

Breakdown:

  • -u or --set-upstream: Links your local branch to the remote branch, enabling automatic tracking.
  • origin: The name of the remote repository (default is origin).
  • <branch-name>: Replace with your local branch name.

Example Workflow:

  1. Create and switch to a new local branch:
   git checkout -b feature/login
  1. Commit some changes:
   git add .
   git commit -m "Add login page"
  1. Push to the remote repository and set tracking:
   git push -u origin feature/login

What This Does:

  • Creates the remote branch feature/login (if it doesn’t exist).
  • Sets up tracking so future commands like git pull/git push work without specifying the remote branch.

Verify Tracking:

git branch -vv
# Output:
# * feature/login  a1b2c3d [origin/feature/login] Add login page

Key Notes:

  • First Push: Use -u only once. Subsequent pushes can use git push alone.
  • Existing Branches: If the remote branch already exists, use git branch --set-upstream-to=origin/<branch-name> to link it retroactively.

Leave a Reply

Your email address will not be published. Required fields are marked *