如何使.bashrc 别名在 vim shell 命令中可用? (: ! ...)

我在 Mac 上使用 bash 其中一个化名是这样的

alias gitlog='git --no-pager  log -n 20 --pretty=format:%h%x09%an%x09%ad%x09%s --date=short --no-merges'

但是,当我做什么

 :! gitlog

我明白

/bin/bash: gitlog: command not found

我知道我可以在我的.gitconfig 中添加这样的别名

[alias]
co = checkout
st = status
ci = commit
br = branch
df = diff

但是我不想把我所有的 bash 别名都添加到. gitconfig 中,那不是 DRY。

还有更好的解决办法吗?

23159 次浏览

Bash doesn’t load your .bashrc unless it’s interactive.

Run :set shellcmdflag=-ic to set it to interactive for the current session.

To make the setting permanent, add set set shellcmdflag=-ic to the end of your .vimrc file.

Use a bang (!) before sending a command to shell. For example: :! cd folder/.

Note that depending on how your bash dotfiles are configured you may want to use the -l rather than the -i option. This will launch the shell as login shell.

I don't feel too comfortable with setting the -i option, as it has quite some impact and I am using the shell often from vim. What I'd do instead is something like :!bash -c ". ~/.alias; gitlog"

I know this question was already previously "answered", but I have a problem with the answer. The shell doesn't need to be set to interactive in Vim. See this thread for an alternative answer without having to exit an interactive shell.

If you want non-interactive shell (as default) but expansion of bash aliases, put your alias definitions in a file, e.g. .bash_aliases and explicitly enable alias expansion in this file:

shopt -s expand_aliases
alias la='ls -la'

Then add this to your .vimrc so the aliases file is actually read each time you run a shell command from within vim:

let $BASH_ENV = "~/.bash_aliases"

This solution was suggested by "Jakob". See the link below for the original. I tested this on Mac OS X 10.9 and it worked flawlessly!

vim -- not recognizing aliases when in interactive mode?

I know it may be an old question, however none of the above answers worked for me as desired. So for the ones who came here from googling and for (oh-my-)zsh users:

My solution to this was as simply as copying .zshrc to .zshenv - as per http://zsh.sourceforge.net/Intro/intro_3.html:

`.zshenv' is sourced on all invocations of the shell, unless the -f option is set. It should contain commands to set the command search path, plus other important environment variables. `.zshenv' should not contain commands that produce output or assume the shell is attached to a tty.

So $ cp ~/.zshrc ~/.zshenv will do the thing.