Issue
I'm trying to write a Bash function to essentially alias deleting a local and a remote Git branch. I'd like it to be run like so:
$ 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>
Here's what I've got so far:
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
}
I'd also love to abstract the git branch -d
and git push origin --delete
calls to other functions to avoid duplication, but I'm having a hard time doing that in Bash.
Solution
Update
# 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
}
Original
Alright, here's something that works:
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
}
Answered By - h.and.h Answer Checked By - Gilberto Lyons (WPSolving Admin)