批量管理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即可查看

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    $ 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内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/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基础之脚本执行,命令别名以及快捷键等