Some Useful Git Commands


List of useful GIT commands, used largely for our own reference. But hopefully it’ll help out some wandering Googler.

  • Useful config changes:
    git config --global user.name "James Brown"               # set the editing user's name
    git config --global user.email "jamesbrown@theapollo.com" # set the editing user's email
    git config --global core.editor vim                       # set the default editor (e.g. for commits) to vim
    cat ~/.gitconfig         # show the james' config file
    

  • Init empty repository via SSH on, say, shared hosting (like, say, HostGator):
    mkdir -p ~/git/myproject.git
    cd ~/git/myproject.git
    git init --bare
    

  • Convert local, existing source files to GIT repo.
    cd myproject
    git init
    git remote add origin ssh://username@mysharedhosting.com/~/git/myproject.git
    git add .
    git commit -m "Initial Commit"
    git push --set-upstream origin master
    

  • To add a remote origin which is on a non-standard port:
    git remote add origin ssh://username@mysharedhosting.com:2222/~/git/myproject.git
    

  • If you want to have the changes go live after you’ve committed your remote repository, edit ~/git/myproject.git/hooks/post-update and make it executable (chmod +x post-update):
    #!/bin/sh
    #
    echo
    echo "**** Pulling changes into PRODUCTION ****"
    echo
    cd ~/public_html || exit
    unset GIT_DIR
    git pull origin master
    exec git-update-server-info
    

  • For the last one to work, your public_html dir will have to be setup as a git repo as well, with the remote repo set to the server’s git dir:
    cd ~/public_html
    git init
    git remote add origin ~/git/myproject.git
    

  • Show the staging area (those which have been “git add”ed but not yet “git commit”ted):
    git diff --cached
    git diff --cached --stat    # only show the files which have changed
    

  • Remove file from the staging area:
    git rm --cached SOME/FILENAME
    

  • Remove some directory from the staging area:
    git rm --cached -r -f SOME/DIR
    

  • Reset/clean the staging area (like you never git added in the first place):
    git reset # shorthand for git reset --mixed
    

  • If you want to pull one file and discard the local changes, go with:
    git checkout FILENAME

  • Amend the last commit message, before having been “git push”ed
    git commit --amend

Credits where due: