经常用git,在实际操作中有一些较难但非常使用的命令,将在本文予以累积。分为比较、整理、易用性等章节。

比较

比较关键性不同

比较两次版本的不同,如果需要忽略空格和tab,可以加上-w参数

git diff -w -- ./foo/bar.php

比较两个不同的commit之间的异同

git diff HEAD~5..HEAD -w

整理

将当前分支的某个目录独立成新的git项目

git filter-branch --subdirectory-filter [dir1]

去掉项目中的某些文件或目录

git filter-branch --tree-filter 'rm -rf tools/' --prune-empty -f

修改提交者姓名邮箱

git filter-branch --commit-filter '
        if [ "$GIT_AUTHOR_EMAIL" = "foo@localhost" ];
        then
                GIT_AUTHOR_NAME="foo";
                GIT_AUTHOR_EMAIL="foo@example.com";
                git commit-tree "$@";
        else
                git commit-tree "$@";
        fi' HEAD

获取远程所有分支

git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all

易用性

设定帐号密码不用重复输入

# 设定5分钟内帐号密码不用重复输入
git config --global credential.helper cache --timeout=300

在终端自动提示当前所在分支

1.进入你的home目录

cd ~

2.在~/.bashrc加入内容

cat >> ~/.bashrc <<EOF
function git_branch {
  branch="`git branch 2>/dev/null | grep "^\*" | sed -e "s/^\*\ //"`"
  if [ "${branch}" != "" ];then
      if [ "${branch}" = "(no branch)" ];then
          branch="(`git rev-parse --short HEAD`...)"
      fi
      echo " ($branch)"
  fi
}
export PS1='\u@\h \[\033[01;36m\]\W\[\033[01;32m\]$(git_branch)\[\033[00m\] \$ '
EOF

3.保存退出,执行加载命令

source ~/.bashrc

Mac 下面启动的 shell 是 login shell,所以加载的配置文件是.bash_profile,不会加载.bashrc。如果你是 Mac 用户的话,需要再执行下面的命令,这样每次开机后才会自动生效:

echo "[ -r ~/.bashrc ] && source ~/.bashrc" >> .bash_profile

按TAB键自动提示命令

将脚本放入家目录

cd ~
wget https://github.com/git/git/raw/master/contrib/completion/git-completion.bash --no-check-certificate
echo "source ~/git-completion.bash" >> ~/.bashrc
source git-completion.bash

远程

清理本地分支

当本地上记录的远程分支和实际的远程分支不一致的时候,可以运行 prune 命令,将远程上已经不存在的分支在本地缓存的记录清理掉。

git remote prune origin

标签: git

添加新评论