How to Push to GitHub: Simple Git Commands Explained
To push code to GitHub, use the
git push command after committing your changes locally with git commit. This sends your changes from your local repository to the remote GitHub repository.Syntax
The basic syntax to push changes to GitHub is:
git push <remote> <branch>
Here, <remote> is usually origin, the default name for your GitHub repository, and <branch> is the branch name like main or master.
bash
git push origin mainExample
This example shows how to add a file, commit it, and push to GitHub on the main branch.
bash
echo "Hello GitHub" > hello.txt # Initialize git repository if not done # git init git add hello.txt git commit -m "Add hello.txt" git push origin main
Output
[main abc1234] Add hello.txt
1 file changed, 1 insertion(+)
create mode 100644 hello.txt
Enumerating objects: 3, done.
Counting objects: 100% (3/3), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 250 bytes | 250.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To github.com:username/repository.git
abc1234..def5678 main -> main
Common Pitfalls
Common mistakes when pushing to GitHub include:
- Not committing changes before pushing.
- Trying to push to a branch that does not exist on the remote.
- Not setting the remote repository URL correctly.
- Authentication errors due to missing or incorrect credentials.
Always commit your changes first and verify your remote with git remote -v.
bash
git push origin main # Error: failed to push some refs because the remote contains work that you do not have locally. # Fix by pulling first: git pull origin main # Then push again: git push origin main
Quick Reference
Here is a quick cheat sheet for pushing to GitHub:
| Command | Description |
|---|---|
| git add . | Stage all changes for commit |
| git commit -m "message" | Commit staged changes with a message |
| git push origin main | Push commits to the main branch on GitHub |
| git remote -v | Show remote repository URLs |
| git pull origin main | Fetch and merge changes from GitHub |
Key Takeaways
Always commit your changes locally before pushing to GitHub.
Use 'git push origin branch-name' to send changes to the remote repository.
Verify your remote repository URL with 'git remote -v' to avoid errors.
Pull remote changes first if push is rejected due to conflicts.
Authentication is required; set up SSH keys or use a personal access token.