[리눅스/윈도] git branch, checkout 응용 스크립트

2023. 5. 6. 18:37버전관리 및 빌드/Git

작성일 : 2021. 9. 15.

 

사용법)

상위 디렉토리에서 전체 프로젝트에 대해 활성화된 로컬 브랜치를 확인하려고 할 때
[/mnt/d/backend]$ git_branch.sh
repoPrj0 -> * dev
repoPrj1 -> * newDev
repoPrj2 -> * dev
프로젝트 디렉토리에서 로컬 브랜치 목록을 확인할 때
[/mnt/d/backend/repoPrj1]$ git_branch.sh
  dev
* newDev
  oldWork

 

스크립트 소스)

#!/bin/bash
# Copyright [2021-2022] [한정훈 & papercraft.tistory.com & 종이와 쉼터]
# 
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#    http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ------------------------------------------------------------
# 본 BASH 스크립트는 아파치 라이선스 버전 2.0(라이선스)에 따라 라이선스가 부여됩니다.
# 라이선스를 준수하지 않는 한 이 파일을 사용할 수 없습니다.
# 다음에서 라이선스 사본을 얻을 수 있습니다.
# 
#  http://www.apache.org/licenses/LICENSE-2.0
# 
# 관련 법률에서 요구하거나 서면으로 동의하지 않는 한 소프트웨어
# 라이선스에 따라 배포되는 것은 "있는 그대로" 배포되며,
# 명시적이든 묵시적이든 어떠한 종류의 보증이나 조건도 제공하지 않습니다.
# 라이선스에 따른 권한 및 제한 사항을 관리하는 특정 언어는 라이선스를 참조하십시오. 
# 
# 퍼갈 때는 출처를 남겨주세요.

PREV_WD=$PWD
if [ $# -gt 0 ];then
	if [ $# -gt 1 ];then # has $1, $2 - project dir, new branch name
		if [ -d $1 ] && [ -d $1"/.git" ];then # 'repoPrj2...'
			cd $1
			git checkout -b $2
			git branch --set-upstream-to=origin/dev $1
			cd $PREV_WD
			exit 0
		elif [ -d "../"$1 ] && [ -d "../"$1"/.git" ];then # $PWD == $1
			git checkout -b $2
			git branch --set-upstream-to=origin/dev $1
			cd $PREV_WD
			exit 0
		else
			echo -e "error - parameters unmatched\n"
			exit 1
		fi
	elif [ -d ".git" ];then # has $1 only - new branch name
		DIR_NM=$(pwd | awk -F'/' '{print $NF}')
		if [ $DIR_NM != $1 ];then # do not make a branch with same name
			git checkout -b $1
			git branch --set-upstream-to=origin/dev $1
			cd $PREV_WD
		else
			git branch
			exit 0
		fi
	elif [ -d $1 ] && [ -d $1"/.git" ];then # 'repoPrj2...'
		cd $1
		git branch
		cd ..
		exit 0
	else
		echo -e "error - no ".git" \n"
		exit 1
	fi
elif [ -d ".git" ];then
	git branch
else
	PRJ_DIR=$(find . -maxdepth 1 -type d -name 'repoPrj*' | sed 's/.\///g')
	for i in ${PRJ_DIR[@]};do cd $i;git branch | grep '^*' | xargs echo $i ' -> ';cd ..;done
fi