Shell工具-git常见操作

83 阅读1分钟

使用方法

1、commit

# 通过交互的方式输入 commit comment
git.sh c

2、push

git p
# 强制提交
git pf

3、pull

git.sh pf

4、log

# 通过交互的方式输入 log num
git.sh l

5、rebase

# 通过交互的方式输入 commit num
git.sh r

6、stash

git.sh s
# 弹出stash记录
git.sh sp

脚本

#!/bin/bash
declare branch=$(git branch | grep "*" | awk -F " " '{print $2}')
help() {
	echo "sh $0 [c|pl|p|pf|l|r|s|sp]"
	echo "c: commit"
	echo "pl: pull"
	echo "p: push"
	echo "pf: push force"
	echo "l: log"
	echo "r: rebase"
	echo "s: stash"
	echo "sp: stash pop"
	exit -1
}

check_git_status() {
	content=$(git status)
	res="$(echo $content | grep "无文件要提交,干净的工作区")"
	[ -z "$res" ] && return 1 || return 0
}

commit_op() {
	check_git_status
	if [ $? -ne 0 ];then
		git add .
		read -p "please add commit comment: " comment
		git commit -m "$comment"
	else 
		echo "no change,no commit"
	fi
}

push_op() {
	commit_op
	git push origin $branch
}

push_force_op() {
	commit_op
	git push origin $branch --force
}

pull_op() {
	commit_op
	git pull origin $branch
}

check_return_input_num() {
	use="$1"
	read -p "Please enter the number of $use: " num
	echo $num | grep -q '[^0-9]' 
	if [ $? -eq 0 ];then
		echo "when using log, please specify specific numbers. currently: $num"
		exit -1
	fi
	echo "$num"
}

log_op() {
	num=$(check_return_input_num "log display")
	git log --pretty=oneline -$num
}


rebase() {
	num=$(check_return_input_num "rebase commit")
	git rebase -i HEAD~$num
}

stash_op() {
	git stash
}

stash_op() {
	git stash_pop
}

main() {
	[ $# -eq 0 ] && help
	
	op=$1
	case $op in
		c) commit_op;;
		pl) pull_op;;
		p) push_op;;
		pf) push_force_op;;
		l) log_op 10;;
		r) rebase;;
		s) stash_op;;
		sp) stash_pop_op;;
		*) help;;
	esac
}

main $@