我试图编写一个bash函数来本质上别名删除本地和远程git分支。我希望它像这样运行:
$ db -r <branch_name> // deletes remote branch with name <branch_name>
$ db -l <branch_name> // deletes local branch with name <branch_name>
$ db -lr <branch_name> // deletes local and remote with <branch_name>
这是到目前为止我得到的:
db () {
declare opt
declare OPTARG
declare OPTIND
has_l_option=false
has_r_option=false
while getopts :r:l: opt; do
case $opt in
r) has_r_option=true ;;
l) has_l_option=true ;;
:) echo "Missing argument for option -$OPTARG"; exit 1;;
\?) echo "Unknown option -$OPTARG"; exit 1;;
esac
done
shift $(( OPTIND - 1 ))
if $has_l_option && $has_r_option; then
git branch -d $1
git push origin --delete $1
elif $has_l_option; then
git branch -d $1
elif $has_r_option; then
git push origin --delete $1
else
echo "Something went wrong"
fi
}
我也很想抽象git分支-d和git push origin --delete调用其他函数以避免重复,但是我很难在bash中做到这一点:/
感谢您的帮助!
答案 0 :(得分:1)
# Takes -r or -l and a branch name
# and deletes the local and/or remote branch with that name
db () {
declare opt
declare OPTARG
declare OPTIND
BRANCH_NAME="$2"
HAS_L_OPTION=false
HAS_R_OPTION=false
while getopts :rl opt; do
case "$opt" in
r) HAS_R_OPTION=true ;;
l) HAS_L_OPTION=true ;;
:) echo "Missing argument for option -$OPTARG"; return 1;;
\?) echo "Unknown option -$OPTARG"; return 1;;
esac
done
shift $(( OPTIND - 1 ))
perform_branch_deletes_given "$BRANCH_NAME" "$HAS_L_OPTION" "$HAS_R_OPTION"
echo "All done!"
}
# Helper
perform_branch_deletes_given () {
BRANCH_NAME="$1"
L="$2"
R="$3"
if "$L"; then
git branch -D "$BRANCH_NAME"
fi
if "$R"; then
git fetch -p origin # prune local "cache" of remote branches
echo "Local 'cache' of remote branches pruned"
git push origin --delete "$BRANCH_NAME"
fi
}
好的,这是可行的:
db () {
declare opt
declare OPTARG
declare OPTIND
has_l_option=false
has_r_option=false
while getopts :rl opt; do
case $opt in
r) has_r_option=true ;;
l) has_l_option=true ;;
:) echo "Missing argument for option -$OPTARG"; exit 1;;
\?) echo "Unknown option -$OPTARG"; exit 1;;
esac
done
shift $(( OPTIND - 1 ))
if $has_l_option; then
git branch -d $1
fi
if $has_r_option; then
git push origin --delete $1
fi
}