DEV Community

Cover image for Created a Shell Script to Simplify Git Commands
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Created a Shell Script to Simplify Git Commands

This article was originally published on bmf-tech.com.

Overview

I created git alias commands in .bashrc, but since it was incomplete, I improved it.

While the previous alias made using git commands somewhat comfortable, I thought it was necessary to improve the requirement of typing the branch name every time I executed a git command, so I solved it using select.

Source

I thought it would be good to loop through the values of git branch with select, but since it also retrieves file names in addition to branch names, it needed some processing. I referred to an article that was doing something similar.

The commands I created are:

  • Checkout a local branch
  • Bring a remote branch to local
  • Delete a local branch
#!/bin/sh

#checkout a local branch
function gitCheckoutLocalBranch() {
        branches=`git branch | grep -v -e"^\*" | tr -d ' '`

        PS3="Select branch > "
        echo 'Branch list:'

        select branch in ${branches}
        do
                stty erase ^H
                git checkout ${branch}
                break
        done
}
alias g-c=gitCheckoutLocalBranch

# create a new branch and checktout a remote branch
function gitCreateAndCheckoutRemoteBranch() {
        branches=`git branch -r | grep -v -e"^\*" | tr -d ' '`

        PS3="Select branch > "
        echo 'Branch list:'

        select branch in ${branches}
        do
                stty erase ^H
                echo -n "What is the new branch name?"
                read new_branch_name
                git checkout -b ${new_branch_name} ${branch}
                break
        done
}
alias g-c-b-r=gitCreateAndCheckoutRemoteBranch

# delete a local branch
function gitDeleteLocalBranch() {
        branches=`git branch | grep -v -e"^\*" | tr -d ' '` 

        PS3="Select branch > "
        echo 'Branch list:'

        select branch in ${branches}
        do
                stty erase ^H
                git branch -D ${branch}
                break
        done
}
alias g-b-d=gitDeleteLocalBranch
Enter fullscreen mode Exit fullscreen mode

I wanted to change the color of the options output by select, but I didn't know how, so I postponed it.

Thoughts

This source is available at github - bmf-san/my-scripts.

References

Top comments (0)