Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

Git tips

Use tig -- a nice command line tool.  It can be installedon CENTOS directly.

Lately I discovered tig and found it very useful. There are some cases I'd wish it does A or B but most of the time it's rather neat.

For your case, tig <filename> might be what you're looking for.

http://jonas.nitro.dk/tig/

 

List files in local git repo

This command:

git ls-tree --full-tree -r HEAD

lists all of the already committed files being tracked by your git repo.

--karlphillip

git log

One of the best ways to improve the utility of git log is to create proper commit messages. The git commit help page includes a DISCUSSION section thatís worth reading. It states, ďThough not required, itís a good idea to begin the commit message with a single short (less than 50-character) line summarizing the change, followed by a blank line and then a more thorough description

Using this format will make a huge difference in your history messages.

You can get a summary of your commits via git log --oneline.

When you ran git init, Git made a default branch for you to put your commits into. This default branch has a name, and that name is master \

git log --follow -p -- file

This will show the entire history of the file (including history beyond renames and with diffs for each change).

In other words, if the file named bar was once named foo, then git log -p bar (without the --follow option) will only show the file's history up to the point where it was renamed -- it won't show the file's history when it was known as foo. Using git log --follow -p bar will show the file's entire history, including any changes to the file when it was known as foo. The -p option ensures that diffs are included for each change.

git whatchanged -p filename is also equivalent to git log -p filename in this case.

You can also see when a specific line of code inside a file was changed with git blame filename. This will print out a short commit id, the author, timestamp, and complete line of code for every line in the file. This is very useful after you've found a bug and you want to know when it was introduced (or who's fault it was).

To show what revision and author last modified each line of a file:
git blame filename

or if you want to use the powerful blame GUI:

git gui blame filename
Summary of other answers after reading through them and playing a bit:

The usual command line command would be

git log --follow --all -p dir/file.c

But you can also use either gitk (gui) or tig (text-ui) to give much more human-readable ways of looking at it.

gitk --follow --all -p dir/file.c

tig --follow --all -p dir/file.c

Under debian/ubuntu, the install command for these lovely tools is as expected :

sudo apt-get install gitk tig

And I'm currently using:

alias gdf='gitk --follow --all -p'

so that I can just type gdf dir to get a focussed history of everything in subdirectory dir.

Add this alias to your .gitconfig:
[alias]
    lg = log --all --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'\n--abbrev-commit --date=relative

And use the command like this:

> git lg
> git lg -- filename

The output will look almost exactly the same as the gitk output. Enjoy.

  • After I ran that lg shortcut, I said (and I quote) "Beautiful!". However, note that the "\n" after "--graph" is an error. Ė jmbeck Jul 22 '13 at 14:40
  • 3
    Also can be used git lg -p filename - it returns a beautiful diff of searched file. Ė Egel Mar 27 '15 at 12:11
I wrote git-playback for this exact purpose
pip install git-playback
git playback [filename]

This has the benefit of both displaying the results in the command line (like git log -p) while also letting you step through each commit using the arrow keys (like gitk).

 

git log --stat

 

git show head

git show HEAD

provides nice listing of recent changes.

git diff

git diff -U <filename> give you a unified diff.

It should be colored on red and green. If it's not, run: git config color.ui auto first.

 

Using branches

In the course of any project, youíll often need additional lines of development. The master branch  typically represents the working code-base. The code in master is generally clean, builds properly, can be deployed to the production environment, and so forth. Therefore, you typically donít want to develop on master directly. Instead, you want to create a copy of this master branch and work on that.

Branches provide a way to isolate changes from the rest of the code base. In the previous section, you created a new branch right from the tip of master. This branch could represent a new feature that youíre developing. But perhaps more common is the need to create a branch to develop a fix. Fixes tend to be made on an earlier part of your repositoryís history.

List the branches that are in your repository:

git branch

This should return a single line, * master. To create a branch, type the following:

git branch new_feature

Now type this:

git branch

You can add and commit change with a comment using one liner

git commit -a -m "A small update to readme."

Deleting branches

Sometimes you need to delete branches. Remember that branches are forks in the road. Some branches youíll walk down only a short way. You create branches because you want to try something, but sometimes your experiment doesnít succeed.

You may inadvertently create a branch by accident. As you saw in the previous section, branches are easy to create. Deleting is just as easy. To delete a branch, use the -d switch of git branch. Remember that you deleted a branch already in the first TRY IT NOW of this chapter.

Try it Now

In the command-line window, in the math directory, type this:

git checkout master
git branch -d fixing_readme

To see what branches you have, type this:

git branch

The git diff command has an interesting syntax you can use to determine the differences between two branches.

 
Try it Now

In the merge sample directory from the preceding section, type this:

git diff master...bugfix

git remote allows you to examine and update the remote.  git ls-remote command  lets you know if your local repository and your original (remote) repository are out of sync. This chapter will help you understand Gitís collaboration model, and will make the next two chapters on git push and git pull clearer.

Auto-Completion

If you use the Bash shell, Git comes with a nice auto-completion script you can enable. Download it directly from the Git source code at https://github.com/git/git/blob/master/contrib/completion/git-completion.bash . Copy this file to your home directory, and add this to your .bashrc file:

source ~/git-completion.bash

If you want to set up Git to automatically have Bash shell completion for all users, copy this script to the /opt/local/etc/bash_completion.d directory on Mac systems or to the /etc/bash_completion.d/ directory on Linux systems. This is a directory of scripts that Bash will automatically load to provide shell completions.

If youíre using Windows with Git Bash, which is the default when installing Git on Windows with msysGit, auto-completion should be preconfigured.

Press the Tab key when youíre writing a Git command, and it should return a set of suggestions for you to pick from:

$ git co<tab><tab>
commit config

Git Aliases

Git doesnít infer your command if you type it in partially. If you donít want to type the entire text of each of the Git commands, you can easily set up an alias for each command using git config. Here are a couple of examples you may want to set up:

$ git config --global alias.co checkout
$ git config --global alias.br branch
$ git config --global alias.ci commit
$ git config --global alias.st status

This means that, for example, instead of typing git commit, you just need to type git ci. As you go on using Git, youíll probably use other commands frequently as well; in this case, donít hesitate to create new aliases.

This technique can also be very useful in creating commands that you think should exist. For example, to correct the usability problem you encountered with unstaging a file, you can add your own unstage alias to Git:

$ git config --global alias.unstage 'reset HEAD --'

This makes the following two commands equivalent:

$ git unstage fileA
$ git reset HEAD fileA

This seems a bit clearer. Itís also common to add a last command, like this:

$ git config --global alias.last 'log -1 HEAD'

This way, you can see the last commit easily:

$ git last
commit 66938dae3329c7aebe598c2246a8e6af90d04646
Author: Josh Goebel <[email protected]>
Date:   Tue Aug 26 19:48:51 2008 +0800

    test for current head

    Signed-off-by: Scott Chacon <[email protected]>

As you can tell, Git simply replaces the new command with whatever you alias it to. However, maybe you want to run an external command, rather than a Git subcommand. In that case, you start the command with a ! character. This is useful if you write your own tools that work with a Git repository. We can demonstrate by aliasing git visual to run gitk:

$ git config --global alias.visual '!gitk'

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

Top articles

Sites

...

Collection of git-tips, want to add your tips? Checkout contributing.md

Everyday Git in twenty commands or so

git help everyday

Show helpful guides that come with Git

git help -g

Overwrite pull

git fetch --all && git reset --hard origin/master

List of all files till a commit

git ls-tree --name-only -r <commit-ish>

Git reset first commit

git update-ref -d HEAD

List all the conflicted files

git diff --name-only --diff-filter=U

List of all files changed in a commit

git diff-tree --no-commit-id --name-only -r <commit-ish>

Unstaged changes since last commit

git diff

Changes staged for commit

git diff --cached

Show both staged and unstaged changes

git diff HEAD

List all branches that are already merged into master

git checkout master && git branch --merged

Quickly switch to the previous branch

git checkout -

Remove branches that have already been merged with master

git branch --merged | grep -v '\*' | xargs -n 1 git branch -d

List all branches and their upstreams, as well as last commit on branch

git branch -vv

Track upstream branch

git branch -u origin/mybranch

Delete local branch

git branch -d <local_branchname>

Delete remote branch

git push origin --delete <remote_branchname>

Alternatives:

git push origin :<remote_branchname>

Undo local changes with the last content in head

git checkout -- <file_name>

Revert: Undo a commit by creating a new commit

git revert <commit-ish>

Reset: Discard commits, advised for private branch

git reset <commit-ish>

Reword the previous commit message

git commit -v --amend

Amend author.

git commit --amend --author='Author Name <[email protected]>'

Reset author, after author has been changed in the global config.

git commit --amend --reset-author --no-edit

Changing a remote's URL

git remote set-url origin <URL>

Get list of all remote references

git remote

Alternatives:

git remote show

Get list of all local and remote branches

git branch -a

Get only remote branches

git branch -r

Stage parts of a changed file, instead of the entire file

git add -p

Get git bash completion

curl http://git.io/vfhol > ~/.git-completion.bash && echo '[ -f ~/.git-completion.bash ] && . ~/.git-completion.bash' >> ~/.bashrc

What changed since two weeks?

git whatchanged --since='2 weeks ago'

See all commits made since forking from master

git log --no-merges --stat --reverse master..

Pick commits across branches using cherry-pick

git checkout <branch-name> && cherry-pick <commit-ish>

Find out branches containing commit-hash

git branch -a --contains <commit-ish>

Alternatives:

git branch --contains <commit-ish>

Git Aliases

git config --global alias.<handle> <command> 
git config --global alias.st status

Saving current state of tracked files without commiting

git stash

Alternatives:

git stash save

Saving current state including untracked files

git stash save -u

Alternatives:

git stash save --include-untracked

Show list of all saved stashes

git stash list

Apply any stash without deleting from the stashed list

git stash apply <stash@{n}>

Apply last stashed state and delete it from stashed list

git stash pop

Alternatives:

git stash apply stash@{0} && git stash drop stash@{0}

Delete all stored stashes

git stash clear

Alternatives:

git stash drop <stash@{n}>

Grab a single file from a stash

git checkout <stash@{n}> -- <file_path>

Alternatives:

git checkout stash@{0} -- <file_path>

Show all tracked files

git ls-files -t

Show all untracked files

git ls-files --others

Show all ignored files

git ls-files --others -i --exclude-standard

Create new working tree from a repository (git 2.5)

git worktree add -b <branch-name> <path> <start-point>

Create new working tree from HEAD state

git worktree add --detach <path> HEAD

Untrack files without deleting

git rm --cached <file_path>

Alternatives:

git rm --cached -r <directory_path>

Before deleting untracked files/directory, do a dry run to get the list of these files/directories

git clean -n

Forcefully remove untracked files

git clean -f

Forcefully remove untracked directory

git clean -f -d

Alternatives:

git clean -df

Update all the submodules

git submodule foreach git pull

Show all commits in the current branch yet to be merged to master

git cherry -v master

Alternatives:

git cherry -v master <branch-to-be-merged>

Rename a branch

git branch -m <new-branch-name>

Alternatives:

git branch -m [<old-branch-name>] <new-branch-name>

rebases 'feature' to 'master' and merges it in to master

git checkout feature && git rebase @{-1} && git checkout @{-2} && git merge @{-1}

Archive the master branch

git archive master --format=zip --output=master.zip

Modify previous commit without modifying the commit message

git add --all && git commit --amend --no-edit

Prunes branches that have been deleted in the remote.

git fetch -p

Alternatives:

git remote prune origin

Retrieve the commit hash of the initial revision.

 git rev-list --reverse HEAD | head -1

Visualize the version tree.

git log --pretty=oneline --graph --decorate --all

Alternatives:

gitk --all

Deploying git tracked subfolder to gh-pages

git subtree push --prefix subfolder_name origin gh-pages

Adding a project to repo using subtree

git subtree add --prefix=<directory_name>/<project_name> --squash [email protected]:<username>/<project_name>.git master

Get latest changes in your repo for a linked project using subtree

git subtree pull --prefix=<directory_name>/<project_name> --squash [email protected]:<username>/<project_name>.git master

Export a branch with history to the a file.

git bundle create <file> <branch-name>

Import from a bundle

git clone repo.bundle <repo-dir> -b <branch-name>

Get the name of current branch.

git rev-parse --abbrev-ref HEAD

Ignore one file on commit (e.g. Changelog).

git update-index --assume-unchanged Changelog; git commit -a; git update-index --no-assume-unchanged Changelog

Stash changes before rebasing

git rebase --autostash

Fetch pull request by ID to a local branch

git fetch origin pull/<id>/head:<branch-name>

Alternatives:

git pull origin pull/<id>/head:<branch-name>

Show the most recent tag on the current branch.

git describe --tags --abbrev=0

Show inline word diff.

git diff --word-diff

Donít consider changes for tracked file.

git update-index --assume-unchanged <file_name>

Undo assume-unchanged.

git update-index --no-assume-unchanged <file_name>

Clean the files from .gitignore.

git clean -X -f

Restore deleted file.

git checkout <deleting_commit>^ -- <file_path>

Restore file to a specific commit-hash

git checkout <commit-ish> -- <file_path>

Always rebase instead of merge on pull.

git config --global branch.autosetuprebase always

List all the alias and configs.

git config --list

Make git case sensitive.

git config --global core.ignorecase false

Auto correct typos.

git config --global help.autocorrect 1

Check if the change was a part of a release.

git name-rev --name-only <SHA-1>

Dry run. (any command that supports dry-run flag should do.)

git clean -fd --dry-run

Marks your commit as a fix of a previous commit

git commit --fixup <SHA-1>

squash fixup commits normal commits.

git rebase -i --autosquash
Here are a few Git learning resources to check out:

Tip 2: Start with a Simple Git Workflow

Less is more.

Often, Git is associated with complex workflows. Let me say this though: You donít have to completely master Git in order to instantly reap its benefits.

Git workflows can be extremely simple ó and in a lot of cases "simple" is exactly all you need. Sure, you can use multiple remote repositories, issue pull requests, rebase your changes, etc. but you donít have to if you donít want to.

Starting with a simple workflow also makes it easier to add more complexity later on when you need Gitís more advanced features. The advanced features will be there for you when you need them.

Here are some examples of various Git workflows that you can take ideas and inspiration from:

The overarching point is this: Donít stress out about needing to learn everything about Git. You can start using Git today.

Tip 3: Stop Being Afraid of Making Mistakes

A great thing about Git is that itís almost 100% foolproof.

Keeping the following things in mind should let you sleep easy at night:

  1. Git hardly ever deletes data. Even actions that seem to delete items in reality actually add data to the system that will let you quickly undo deletions.
  2. You can undo almost everything in Git. I encourage you to experiment and explore Git and try out your ideas because this is one of the major benefits of using a version control system.
  3. Every member of your team has a repository cloned on his/her computer. Essentially, this is sort of like a redundant backup of the whole version-controlled project (including the full history) in the very unlikely event you do mess things up big time and canít recover your mistake.

Tip 4: Understand the Concept of Branching

The concept of branching in Git is one of the most useful things you can learn at the start. Branching allows you to keep separate developments of one project possible and is a key component of being an effective Git user.

It may not sound like a big deal at first, but once you fully understand the concept of branching, youíll wonder how you could have possibly lived without this ability.

Although other version control systems use the branching concept too, Git is the first system that really makes it easy and useful.

Git branching

Here are some resources to read that will help you understand the Git branching concept:

Tip 5: Learn About the Staging Area

Version control is most useful when you wrap up only related changes in a commit. This guarantees the commit can be rolled back easily without side-effects. The habit of making frequent commits also helps your coworkers more easily understand the progression of your changes.

Git makes granular commits easier than any other version control system (VCS) because you can determine which changes exactly shall be in the next commit.

A Git feature called staging area makes this possible.

Learn to use and love the staging area because itís one of the most essential and unique components of Git.

Here are some resources about Gitís staging area:

Tip 6: Use a Git GUI

Although using a GUI is definitely not a requirement, I highly recommend it.

Using a GUI makes a lot of tasks easier and gives you a head start.

After all, using Git is not about learning commands and parameters by heart, itís about using Git to improve your coding workflow. If a GUI enhances your coding workflow, thereís no reason to make things harder on yourself.

GitX (L) screenshot

Here are some Git GUIs to check out:

Using a GUI will not relieve you from having to learn the basics, but once youíre happy with the level of Git mastery you have, investigate the tools that will make your life easier.

Tip 7: Commit Yourself to Using Git

Using a new tool can cause a bit of a headache in the first few days. The only way to get through this learning curve is to keep going.

Donít look back; make a full commitment. Introducing Git into your normal coding workflow will soon prove to be one of the biggest and most significant things youíve done in a while.

Avoid making exceptions like "Iíll use Git for these projects, but not for these other projects." At least at first.

The mindset of fully committing to Git gives you more opportunities to practice, makes things simpler because you know that the current project youíre working on is using a version control system, and most importantly makes Git a part of your coding habits.

In the future, youíll see that there are just some situations where you donít need to use Git. You wonít know what those situations are until you use Git in all the situations you can.

At the start of your journey towards Git mastery, make a 100% commitment to it.

Recommended Links

Google matched content

Softpanorama Recommended

Top articles

Sites

git log - View the change history of a file using Git versioning - Stack Overflow



Etc

Society

Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy

Quotes

War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes

Bulletin:

Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law

History:

Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D


Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to to buy a cup of coffee for authors of this site

Disclaimer:

The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: March, 12, 2019