DEV Community

tarohida
tarohida

Posted on

How to define your own custom sub-command to gcloud command

Introduction

I want to run gcloud compute instances list command like this:

gcloud list
Enter fullscreen mode Exit fullscreen mode

I couldn't find how to extend gcloud command offisialiy, so I extend gcloud command by to define alias to .bashrc file.

Define wrapper and alias

Define below in your .bashrc file

gcloud-wrapper () {
    if [ "$1" = "switch" ]; then
        gcloud config set project "$2"
    elif [ "$1" = "list" ]; then
        if [ "$2" = "instances" ]; then
            gcloud compute instances list
        elif [ "$2" = "ip" ]; then
            gcloud compute instances list --format="table(NAME,EXTERNAL_IP)" --filter="EXTERNAL_IP:*"
        fi
    elif [ "$1" = "start" -o "$1" = "up" ]; then
        gcloud compute instances start $2
    elif [ "$1" = "stop" ]; then
        gcloud comupte instances stop $2
    else
        gcloud "$@"
    fi
}

alias gcloud="gcloud-wrapper"
Enter fullscreen mode Exit fullscreen mode

You can extend more to add elif [ "$1" = "list" ]; then line.

If sub command not defined, wrapper run original gcloud command, and you also can use original gcloud command.

How to use in dotfiles

Here is my dotfiles.

You can use solution in your dotfiles.

https://github.com/tarohida/dotfiles/blob/develop/bashrc.d/96-gcloud.sh

My Original Article (in Japanese)

https://qiita.com/taro-hida/items/97c765cf8bfaf967830a

Thank you for your reading.

Top comments (0)