erikbstack
erikbstack

Reputation: 13254

shortcut for long command

Problem

I very often have to interact with github which often leaves me writing a line like the following:

$ git clone [email protected]:<developer>/<project> <foldername> <maybe_other_args>

Now I'd like to minimize this to something like the following (ghc=github clone):

$ ghc <developer>/<project> <foldername> <maybe_other_args>

Tried Solutions

My first approach was a function

ghc () {
    if [ -z "$1" ]; then
        echo "need to set param: <developer>/<project>"
    else
        git clone [email protected]:$1
    fi
}

Neither did I like the verbosity of this approach, nor is it flexible concerning the arguments for git-clone.

My second approach was an alias:

alias ghc="git clone [email protected]:"

But this version doesn't work at all, because after expanding there is a space character between [email protected]: and <developer>/<project>. I like the shortness of that solution, though. How to minimize the command with bash, preferably in one line?

Upvotes: 0

Views: 127

Answers (2)

Jan Hudec
Jan Hudec

Reputation: 76296

The first approach is perfectly flexible. You just have to learn to use "$@" which means all arguments quoted as separate words.

The verbosity in the first case is mostly caused by the error checking. Without it it is just:

ghc() { git clone "[email protected]:$@"; }

which is only 5 more characters as the (non-working) alias. That will combine first argument with the [email protected]: prefix and pass all additional arguments separately just as you wanted.

I don't think the verbosity is a problem when writing it in .profile or .bashrc though.

Note, that in all other shells (like zsh, but also dash) the function body can be any command, not just compound command, so there the function is exactly as long as the alias:

ghc() git clone "[email protected]:$@

unfortunately bash does not accept this.

Upvotes: 3

chepner
chepner

Reputation: 531325

Error-checking can be done less verbosely in bash. But does it really matter how verbose a function's definition is, since you will likely add it to a configuration file once and never look at it again?

ghc () {
    : ${1?need to set param: <developer>/<project>}
    git clone [email protected]:"$@"        
}

One line:

ghc () { git clone [email protected]:"${@?need to set param: <developer>/<project>}"; }

or without any error

Upvotes: 2

Related Questions