zsh - alias with no space at the end of the invocation

Viewed 2668

I would like to have an alias like:

alias gra-bitbucket="gra origin https://gismoranas@bitbucket.org/gismoranas"

so that I can use it like:

gra-bitbucket/some-repo.git

to add a new origin to a git repository (gra is a oh-my-zsh! alias).

My issue is that I don't want to have to write the whole url each time. It must not be an alias, but it would be nice to have a one liner setting.

2 Answers

Source: https://blog.sebastian-daschner.com/entries/zsh-aliases

Put the following in your .zshrc:

# blank aliases
typeset -a baliases
baliases=()

balias() {
  alias $@
  args="$@"
  args=${args%%\=*}
  baliases+=(${args##* })
}

# ignored aliases
typeset -a ialiases
ialiases=()

ialias() {
  alias $@
  args="$@"
  args=${args%%\=*}
  ialiases+=(${args##* })
}

# functionality
expand-alias-space() {
  [[ $LBUFFER =~ "\<(${(j:|:)baliases})\$" ]]; insertBlank=$?
  if [[ ! $LBUFFER =~ "\<(${(j:|:)ialiases})\$" ]]; then
    zle _expand_alias
  fi
  zle self-insert
  if [[ "$insertBlank" = "0" ]]; then
    zle backward-delete-char
  fi
}
zle -N expand-alias-space

bindkey " " expand-alias-space
bindkey -M isearch " " magic-space

Now you can do:

# command aliases
alias jj='java -jar'
alias mcp='mvn clean package'
...

# blank aliases, without trailing whitespace
balias clh='curl localhost:'
...

# "ignored" aliases, not expanded
ialias l='exa -al'
ialias curl='curl --silent --show-error'
...

# global aliases
alias -g L='| less'
alias -g G='| grep'
ialias -g grep='grep --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn}'

Specifically, for your problem, the balias function defined above is what you need:

balias gra-bitbucket="gra origin https://gismoranas@bitbucket.org/gismoranas"
Related