git原来还可以这么用?你不知道的自定义命令

328 阅读1分钟

通过设置git alias来创建自定义命令
当使用的命令行工具不是git的时候,添加!来声明
例如: git config --global alias.pushopen '!bash git-open.sh'

在~/.bashrc 文件里面声明环境变量:

# User configuration @~/.bashrc
export PATH=~/bin:"$PATH"

创建~/bin文件夹。
创建 shell 脚本文件
编写一个自定义提交的shell脚本(git-open.sh):

#!/bin/bash

gitlab=http://gitlab.personal.io

git push $@

remote='origin'

if [[ ! -z $1 ]] && [[ ! "$1" =~ "-" ]];then
        br=$1
fi

address=$(git remote -v | grep $remote | awk -F' ' 'NR==1{print $2}' | awk -F'/' '{print "/"$4"/"$5}')
drs=${address:0:-4}
commit=$(git log -1 | awk 'NR==1{print $2}')

echo "$gitlab$drs"/commit/"$commit"

保存之后执行
git pushopen 时则会自动在命令行打印出最新提交的commit链接。

编写另一个自定义提交的shell脚本(git-clear.sh)

#!/bin/bash

arg=${1:-"-d"}
br=${2:-"fixbug"}

if [[ $arg != "-d" ]] && [[ $arg != '-D' ]]
then
  arg='-d'
  br=$1
fi

git branch | grep $br | xargs git branch $arg

保存后执行 git clear xxx(不传默认为'fixbug') 就可以自动删除 xxx 相关的分支了。

image.png

最近又觉得一个切换分支的操作不错(git-co.sh):

#!/bin/bash

if [[ -z $1 ]]
  then
    echo plz input branch name

  else
    if [[ -z $2 ]]
    then
      if [[ $1 == - ]]
        then git checkout $1
        else 
          br=$(git branch -a | grep $1 | awk -F ' ' 'NR==1{print $1}')
          if [[ -z $br ]]
            then echo not match branch name with: $1
            else git checkout $br
          fi
      fi
    else
      git checkout $*
    fi
fi

设置好之后切换分支就可以模糊切换拉了:

1668756967047_CE643F99-C946-410c-8B46-9C7BFFF0387A.png

甚至你还可以直接全套写下rebase&cherry-pick的流程:

#!/bin/bash

currentBranch=$(git branch | grep '*' | awk -F' ' '{print $2}')
echo ready to pick $(git log -1)
lastCommit=$(git log -1 | awk 'NR==1{print $2}')
git checkout -b $currentBranch-rebase
git branch -D $currentBranch
git checkout $1
git pull -r
git checkout -b $currentBranch
git cherry-pick $lastCommit

这样子在合并分支的时候,commit就会很干净~