0

In my .bashrc, I have aliases:

#Custom aliases
alias gta="git add -A"
alias gtc="git commit -m 'Added files' "

I want to create a new alias that does the command git push origin <branch name>. Earlier it was easy because it was always set to git push origin master.

But now , GitHub has changed master to main for all repositories created after October 2020. Now what I want is that I want to set an alias gtp and it asks me a prompt to use main or master. Depending on the selection, I want the appropriate commands to be executed.

P.S: I know that we can make 2 aliases , one for master and one for main, but just out of curiosity, how to solve the above problem?

2
  • I would use a function in .bashrc (or a shellscript somewhere in PATH) for this purpose.
    – sudodus
    Commented Oct 20, 2020 at 8:04
  • Wouldn't it be simpler to set a default upstream branch for each of your branches? Than you can just alias gtp="git push" Commented Oct 20, 2020 at 9:39

1 Answer 1

2

You could add something like this in your .bashrc:

alias gtp=f

f() {
  arg="$1"
  if [[ -z "$arg" ]] || [[ "$arg" != main && "$arg" != master ]]; then
    echo "Bad argument"
  else
    git push origin "$arg"
  fi
}

Then

~$ . .bashrc
$ gtp
Bad argument

$ gtp foo
Bad argument

$ gtp main
<git doing it's thing>

$ gtp master
<git doing it's thing>

Or @Kusalananda's suggestion

f() {
    arg="$1"

    case $arg in
        main|master)
            git push origin "$arg"
            ;;
        *)
            echo error >&2
    esac
}
2
  • 1
    or case $arg in (main|master) git push origin "$arg";; (*) echo error >&2; esac.
    – Kusalananda
    Commented Oct 20, 2020 at 9:24
  • @Kusalananda better Commented Oct 20, 2020 at 9:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .