• Post category:Git
  • Reading time:6 mins read

Today we will show you how to push code to GitHub using git bash. If you want to publish your work on GitHub then you have to push your code on remote repository.

In other words, push code to the GitHub is used to keep the same work on remote and local repositories.

Way to push code to GitHub

  1. Create repository
  2. Check the status of working tree
  3. Add changes in local repository
  4. Commit the changes
  5. Push changes in remote repository

1. Create repository

Before we start, you have to create a repository / clone of your existing repository from GitHub. If you don’t know how to clone a repository in GitHub then please refer to the link below.

How to clone a Git repository

2. Check the status of working tree

You have to execute the code below to check the status of the working tree.

git status

Use the code below to discard all the changes in the working directory.

git restore .

Use the code below to restore a specific file.

git restore <file>

Note: Above command `git restore` will work before adding changes to the local repository for modified files. It won’t work for local untracked files.

3. Add changes in local repository

If you made any changes then first you have to add these changes in the local repository and stage them for the commit. Below command will help you to do it.

git add .

Use the code below to add an individual file.

git add <file>

Use the code below to add the whole folder.

git add <folder>/*

Let’s say if you added the code by mistake then you can unstage it by the use of the code below.

git reset HEAD <file>

Use the code below to unstage all files.

git reset HEAD

4. Commit the changes

Now it’s time to commit the changes and prepare it for the remote repository so we can push it.

git commit -m "new changes"

If you want to remove the commit then use the code below.

git reset --soft HEAD~1

If you want to remove the commit and discard the changes then use the code below.

git reset --hard HEAD~1

5. Push changes in remote repository

At last, execute the command below to push the changes in remote repository.

git push origin master

Conclusion

Let’s combine all code together in one flow to push code in GitHub.

git status // To check the status of working tree
git add . // To add the changes in local repository	
git commit -m "new changes" // To commit the changes and prepare it for remote repository
git push origin master // To push the changes in remote repository

That’s it for today.
Thank you for reading. Happy Coding!

Leave a Reply