Some git commands and tips

Config before any commit

$ git config --global user.email "email-address"
$ git config --global user.name "user-name"
  or
$ cd /path/to/project/
$ git config --local user.email "email-address"
$ git config --local user.name "user-name"

Setup server end of git repo

$ cd /opt/git
$ mkdir project.git
$ cd project.git
$ git init --bare

Setup fresh local git repo

$ cd project/
$ git init
$ git add .
$ git commit -m "Initial commit"
  or
  git commit -am "Initial commit"
$ git remote add origin <url-of-server-end-git-repo>
$ git push origin master

Clone project and work on it

$ git clone url
$ git pull
  git pull origin master
  git fetch remote-name
  git merge branch-name
$ git status
$ git log
$ git diff
$ git checkout <branch>
$ git checkout -b <new-branch>
$ git branch <new-branch>
$ git branch --list
$ git add <file>
$ git rm <file>
$ git mv <file>
$ git remote
$ git remote -v
$ git remote rm <remote-name>
$ git remote update

Push local branch to remote branch

$ git push <remote> <local-branch>:<remote-branch>
  e.g
$ git push origin hotfix:master

Discard changes

$ git clean -df             => remove all untracked files
$ git checkout -- .         => discard all unstaged changes
$ git checkout -- <file>    => discard unstaged changes for given file
$ git reset -- .            => unstage all staged
$ git reset -- <file>       => unstage the staged file
$ git reset HEAD .          => unstage all staged
$ git reset HEAD -- <file>  => unstage the staged file

Ignore changes

$ git update-index --assume-unchanged <file>
  => stop tracking changes for file that was previously tracked
$ git update-index --no-assume-unchanged <file>
  => resume tracking changes for file that was previously stopped being tracked

Ignore files or directories

# method 1 - use the ".gitignore" file and add patterns there:
  => .gitignore file itself will be tracked and shared among others.
# method 2 - use the ".git/info/exclude" file and add patterns there:
  => exclude file is meant for personal use to ignore patterns.

Rollback old commit

$ git checkout <revision-hash> .

Override previous commit

$ git commit --amend

Ignore all contents of a directory but commit the directory

1) Create a .gitignore file inside the dir
2) Add below two lines:
   => *  
   => !.gitignore

Setup git protocol to allow anonymous read access to git repo

1) Create an empty file in git repo:
   $ cd /path/to/project.git
   $ touch git-daemon-export-ok
2) Start below command as daemon:
   $ git daemon --reuseaddr --base-path=/opt/git/ /opt/git/
     NOTE: the --base-path and the path at the end is the directory where project.git repo is located, if --base-path is used, users do not have to specify the git repo path when cloning the project
3) After that, you can use url to clone project:
   $ git://<ip-or-host-of-git-repo>:9418/project.git

References

BACK TO TOP
Post tagged with: git