首页 > 代码库 > 一个下载git库代码的脚本

一个下载git库代码的脚本

由于每日构建需求, 须要用脚本下载代码, 实现自己主动化编译, 这个脚本是整个系统的一小块功能



#!/bin/bash

#@author Liuyang
#@date 2015-06-23

function help() {
    echo "Usage: $0"
    echo "    First argument should be the git repository‘s address"
    echo "        for example: git@192.168.1.52:android/xiaomeidaojia.git"
    echo "    Second argument should be the branch you want to checkout"
    echo "        for example: dev"
    echo "    If the second argument is not supplied, master will be used as default"
}

# Whether the given branch is in local branches.
function is_in_local_branch() {
    git branch | grep $1 2>&1 > /dev/null
    return $?
}

# Whether the given branch is in remote branches.
function is_in_remote_branch() {
    git branch -r | grep origin/$1 2>&1 > /dev/null
    return $?
}

if [[ $# != 1 && $# != 2 ]]; then
    help
    exit 1
fi

# Judge whether the repository‘s address is valid.
if [[ $1 != *.git ]]; then
    help
    exit 1
fi

# Split the project‘s name
project_name=`echo $(basename $1) | cut -d . -f 1`


if [[ ! -d $project_name ]]; then
    git clone $1
else
    cd $project_name
    git reset HEAD --hard
    git pull

    if [[ $2 == "" ]]; then
        exit
    fi

    is_in_local_branch $2
    if [[ $? == 0 ]]; then
        git checkout $2
        exit
    fi

    is_in_remote_branch $2
    if [[ $? == 0 ]]; then
        git checkout -b $2 origin/$2
    fi
fi



脚本中, 首先推断该git库是否存在, 不存在则克隆该仓库.

否则会回退全部更改, 然后运行拉取操作, 最后会切换到给定分支.


一个下载git库代码的脚本