Using Git

Frequently used Git commands

Git runs entirely on your workstation, and a copy of the entire repository is also on your local hard drive. GitHub, BitBucket, and other providers only give you a storage space to allow you to share your repository with others and provide a web user interface to manage it. You can use any provider’s application on your workstation to manage any of your Git repositories. Many developers use SourceTree, the great application written by Atlassian, the owner of BitBucket, to manage Git repositories on their workstations that are shared at GitHub.

Here are the most frequently used Git commands.

Create the local repository

Initialize a new Git repository in the current directory. This command creates the .git sub-directory to store your repository and its configuration file.

git init

Display the local repository status

Display the list of added, deleted and modified files in the local repository

git status

Display your changes in the files

Display the changes in files since the last git add

git diff

Display the changes in the local stage area after you have executed  git add

git diff --staged

Stage your changes in the local repository

Add your changes to the local stage area

git add .

Save the changes to the local repository

Commit your changes from the local stage area to the local repository with a message

git commit -m "My message"

Edit the last commit message

You can edit the last commit message even after the push.

git commit --amend

When you execute git status you get the message

Your branch and ‘origin/master’ have diverged,
and have 1 and 1 different commits each, respectively.
(use “git pull” to merge the remote branch into yours)
nothing to commit, working tree clean

To synchronize your local repository with the remote server, execute

git pull

The merge window pops up. You can leave the default message, or type your explanation. To save your message and close the window

  1. Press the ESC key on your keyboard
  2. Press the keys (including the colon at the beginning) :wq

Send your changes to the remote repository

Push the changes to the remote repository at GitHub, Bitbucket, or others

git push

Get the latest from the remote repository

Pull the latest changes from the remote repository

git pull

Advanced topics

Push an existing repository from the command line

git remote add origin https://github.com/ORGANIZATION/REPOSITORY_NAME.git
git push -u origin master

Clone a private Git repository from the command line

git clone https://my_username:my_password_or_token@github.com/my_user_name/my_repo_name.git

or use an SSH key, see https://help.github.com/en/articles/connecting-to-github-with-ssh

Branching

Forks and Pull Requests

View an old version of the repository

To view the repository in the state of an old commit and return back to the current state use the “checkout” command

Save the state of the working directory

Temporarily save the current state of the working directory including untracked (new) and ignored files

 git stash -a

List the commits of the repository

git log

Search all commits of a file in a branch

First, select the branch to search in, if it is not the current branch

git checkout BRANCH_NAME
git log --all --full-history -- **/MY_FILE.*

View the old version of the repository

git checkout MY_OLD_COMMIT_SHA

To create a new branch for the restored version and switch to it

git switch -c <new-branch-name>

To switch back to the “main” branch to see the latest version of the repository

git switch main

To switch to the new branch for the restored version of the repository

git switch <new-branch-name>

Create a new branch and continue the work

If you realize, this is the last stable version of the application, create a new branch and develop your project from this point forward. This way you will not lose changes you made after this commit, but you will be able to create new commits based on the working version and merge the new branch back to the “master” branch later.

git checkout -b MY_APP_WORKS_AGAIN_BRANCH

Restore the state of the working directory before the “stash” command

git stash pop

If you want to restore the repository to the state before the “git stash” with the “git stash pop” command and you have created new files, to prevent the accidental deletion of those files, Git will display the error message:

MyPath/File already exists, no checkout
Could not restore untracked files from stash

You also get his message when an ignored file has been created, like the “.DS_Store” file on Mac OS.

Remove ignored files

To remove the ignored files from the work tree execute the following. Please note the upper case “X”.

Dry run to see what will be deleted:

git clean -n -f -X

Delete the files:

git clean -f -X

Remove ignored and untracked files

To remove the ignored files, and new (untracked) files and directories from the working tree, clean the repository with the following. Please note the lower case “x”.

Dry run to see what will be deleted:

git clean -n -f -d -x

Delete the files:

git clean -f -d -x

Rollback

If you have accidentally committed a change and want to roll back the changes you can use the “reset” command. It is very dangerous because it can rewrite history, remove commits, delete files in your working directory, so you can lose your work. The “–mixed” is the default option of the “reset” command, so if no option is specified, that will be executed.

If the change has NOT been pushed to the remote repository (GitHub)

Remove a file from the stage

The “add” command adds files to the “stage”. If you have “add”-ed multiple files and do not want to “commit” one of them together with the rest, remove a file from the “stage”, but keep it in your working directory.

git reset HEAD -- <file>
git reset HEAD -- <directoryName>

Remove the last commit

Move the history back before the last “commit” and all “add”s that are associated with it. You will not lose any changes in your working directory. Use this command if you realize you want to make more changes before the next commit.

git reset HEAD~1

Remove the last commit and lose all changes since that

Restore the files in the repository to the state of the prior “commit”. You will lose all changes you made since that. This command moves the HEAD back one commit, so it deletes the last commit from the history.

git reset --hard HEAD~1

Undo the rollback

If the reset was unnecessary you can undo it for a limited time. Git runs the garbage collector every 30 days, and it removes orphaned commits, so you have 0 to 30 days to undo the rollback. If the garbage collector runs a few minutes after the reset, the changes are lost forever.

To see the list of commit SHAs that the garbage collector not yet deleted

git reflog

To undo the reset of a commit while it is still available

git checkout -b aNewBranchName shaYouDestroyed

If the changes have already been pushed to the remote repository

The “reset” command can cause serious problems for others working in the same repository. Use the “revert” command to correct mistakes. The “revert” command will create a new commit with the state you want without rewriting the history of the repository.

git revert <bad-commit-sha1-id>
git push origin
 

Remove a file form the entire history of the repository

If a file is too big to be uploaded to the remote repository, you may get the error message when you push the repository to the remote:

remote: Resolving deltas: 100%, done.
remote: error: GH001: Large files detected. You may want to try Git Large File Storage – https://git-lfs.github.com.
remote: error: Trace: …
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File … is … MB; this exceeds GitHub’s file size limit of 100.00 MB
To https://github.com/….git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to ‘https://github.com/….git’

You may also want to remove every trace of a file from the history for security reasons.

git filter-branch command

This command rewrites the history of the repository and removes every trace of a file

git filter-branch -f --index-filter 'git rm --cached --ignore-unmatch "MY_TOO_BIG_FILE_NAME"'

git-filter-repo utility

An alternative to remove files is the Python utility git-filter-repo

Clone the git filter repository from https://github.com/newren/git-filter-repo.git

git clone https://github.com/newren/git-filter-repo.git

Copy the git-filter-repo file to a directory in your path

Usage

Open a terminal window in the repository you want to clean

cd MY_REPOSITORY_TO_CLEAN

The git-filter-repo utility selects files from the repository, so to delete those files and keep the rest of the files in the repository, use the --invert-paths option.

To remove files or directories from the repository
git filter-repo --path README.md --path guides/ --path tools/releases --invert-paths

To use wildcards include the --path-glob option
git filter-repo --path-glob 'src/*/data' --invert-paths

To remove multiple files or directories, save the list in a text file and refer to it with the --paths-fom-file option

git-filter-repo --invert-paths --paths-from-file /tmp/delete-from-git-repo.txt --force

BFG Cleaner

An other alternative to git filter-branch to remove files from the repository is at https://rtyley.github.io/bfg-repo-cleaner/

Leave a comment

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