如何在.bashrc中创建vim调用函数?

scr*_*apy 11 vim bash function

环境:debian9 + vim7.4.

   cat .bashrc
   add(){
        echo $(expr $1 + $2)
    }
Run Code Online (Sandbox Code Playgroud)

现在在vim中编辑一个文件

add 1 5 
Run Code Online (Sandbox Code Playgroud)

在命令模式下运行它:w !bash,发生错误.

bash: line 1: add: command not found    
shell returned 127
Run Code Online (Sandbox Code Playgroud)

1. set shellcmdflag=-ic 在/ etc/vim/vimrc和.bashrc以及.vimrc中添加.
2.reboot
3.vim test.sh
进入命令模式
:verbose set shellcmdflag

  shellcmdflag=-ic
        Last set from ~/.vimrc
Run Code Online (Sandbox Code Playgroud)

4.在test.sh中输入两行

ls
add  5  6

:w !bash     
a1.sh       test.py    
bash: line 2: add: command not found    
shell returned 127    
Run Code Online (Sandbox Code Playgroud)

如何使两条线都执行? 在此输入图像描述
在此输入图像描述

:execute '! source ~/.bashrc; source '.expand('%:p')可以发出两个命令:lsadd运行.

重启后,
1.add函数无法调用sh test.sh

sh test.sh
test.sh   #it means that ls command executed
test.sh: 2: test.sh: add: not found  #it means that add function can't be called from  /etc/vim/vimrc or .bashrc  or .vimrc.
Run Code Online (Sandbox Code Playgroud)

2.add函数无法从vim调用!bash %

在此输入图像描述

test.sh    #it means that ls command executed
test.sh: line 2: add: command not found  #it means that add function can't be called from  /etc/vim/vimrc or .bashrc  or .vimrc.

[4]+  Stopped                 vim test.sh
Run Code Online (Sandbox Code Playgroud)

Ing*_*kat 12

问题是Vim默认调用非交互式 shell,并且.bashrc(add只有你定义了你的函数)才会读取交互式shell.

您可以指示Vim使用交互式shell:

:set shellcmdflag=-ic
Run Code Online (Sandbox Code Playgroud)

这可能会使外部命令调用速度变慢(由于评估Bash初始化的开销).

或者,您可以在其他地方定义该功能,因此它始终可用(但这样的地方并不容易;请参阅man bash,尤其是该INVOCATION部分).或者将函数转换为可从PATH访问的单独脚本(例如~/bin/add).


小智 5

问题是您的功能仅限于交互式外壳才能执行,您必须这样做

:!bash -ic "add 1 2"
Run Code Online (Sandbox Code Playgroud)