批量管理Git项目脚本

应用场景: 本地clone有多个git项目,日常维护需要经常修改,又不想每次切换目录,然后pull、push代码…

使用方法:

  1. 创建shell脚本gghelp.sh

  2. 添加alias

    echo "alias gg='~/gghelp.sh'" >> ~/.bashrc

  3. 防止误删除

    sudo chattr +ae gghelp.sh

  4. 用法说明执行gg -x即可查看

    $ gg -x
        Usage: gghelp.sh [-a --add] [-c --commit] [-d --diff]
                         [-e --epush] [-p --pull] [-s --status]
    
        Options:
            -a|--add    execute git add --all
            -c|--commit execute git commit
            -d|--diff   execute git diff
            -e|--epush  execute git push
            -p|--pull   execute git pull
            -s|--add    execute git status (default option)
    

以下为gghelp.sh内容:

#!/usr/bin/env bash

# Git project list
path_list[0]="$HOME/work/repository-01"
path_list[0]="$HOME/work/repository-02"
path_list[0]="$HOME/work/repository-03"
path_list[0]="$HOME/work/repository-04"


# define usage
usage() {
    cat <<EOM
    Usage: $(basename $0) [-a --add] [-c --commit] [-d --diff]
                     [-e --epush] [-p --pull] [-s --status]

    Options:
        -a|--add    execute git add --all
        -c|--commit execute git commit
        -d|--diff   execute git diff
        -e|--epush  execute git push
        -p|--pull   execute git pull
        -s|--add    execute git status (default option)
EOM
    exit 0
}

# get parameters
parmas=`getopt -q -a -o spdace -l status,pull,diff,add,commit,epush -- "$@"`

# Display usage when parameter is abnormal
[ $? -ne 0 ] && usage

# Parameter processing
eval set -- "${parmas}"

# Default execution [-s]
if [ "$#" -le 1 ]; then
    parmas="-s --"
fi

# Directory listing loop
for path in ${path_list[@]};
do

  echo -e "\033[33m \nProject path: $path \n\033[0m"

  for val in ${parmas[*]}; do
    case "$val" in
      -s|--status )
        cd $path
        git status
        shift
        ;;
      -p|--pull )
        cd $path
        git pull
        shift
        ;;
      -d|--diff )
        cd $path
        git diff --exit-code
        shift
        ;;
      -a|--add )
        cd $path
        git add --all
        shift
        ;;
      -c|--commit )
        cd $path
        if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
            read -t 60 -p "Please input commit message: "
            git commit -m "$REPLY"
        fi
        shift
        ;;
      -e|--epush )
        cd $path
        if [ -n "$(git diff origin/master --exit-code)" ]; then
            git push
        else
            echo "Everything up-to-date"
        fi
        shift
        ;;
      -- )
        shift
        break
        ;;
    esac
  done

done
exit

参考资料:
shell脚本中echo显示内容带颜色
Shell读取用户输入
Bash Shell中命令行选项/参数处理
getopts-tutorial
shell基础之脚本执行,命令别名以及快捷键等