Useful git commands

Add a file to the staging area

git add <file>

To add all files in the current directory, use . in place of <file>.

git add .

Commit Changes

Commit changes that are already tracked and staged

git commit -m "<message>"

If you want to add all changes made to tracked files & commit

git commit -a -m "<message>"

# or

git commit -am "<message>"

Amend or change the last commit message

git commit --amend

Amend and add new changes to the last commit

git commit -a --amend
1 Like

Find branches the commit is on

git branch -a --contains <commit>

I wish there was an easy way to reset a github project.

I believe there’s a command for it, but i just normally delete .git folder and re-init the project. I’m assuming that’s what you mean by reset.

1 Like

Reset meaning deleting the .git folder and starting again. This works locally but not on github. Dont remember what happens when this is tried. I think github still keeps the history. I will have to try again.

Yea, its done locally, but what I normally do afterwards is to do a force push to the repo with the delete all remote branch commands.

Apart from that, I believe Gitlab has something to reset the project. I’m not sure about Github.

In my experience as a developer, the most useful git commands(unrelated to pushing to repository) would be git restore . and git stash(as well as git stash apply)

1 Like

Here’s another useful command to list all branches along with the date they were last worked on and the last commit message; you can use the following command:

git for-each-ref --sort=-committerdate refs/heads/ --format='%(committerdate:iso8601) %(refname:short) %(objectname) %(subject)'

This command will output the branches with their last commit date, the branch name, the last commit hash, and the last commit message in descending order of the commit date. Here’s what each part of the command does:

  • git for-each-ref: Iterates over each reference (branch in this case).
  • --sort=-committerdate: Sorts the branches by the date of the last commit in descending order.
  • refs/heads/: Limits the iteration to local branches.
  • --format='%(committerdate:iso8601) %(refname:short) %(objectname) %(subject)': Formats the output to show the commit date in ISO 8601 format, the branch name, the commit hash, and the last commit message (subject).