How to make the vim call function in .bashrc?

后端 未结 5 2040
春和景丽
春和景丽 2021-01-04 05:57

Environment: debian9+vim7.4.

   cat .bashrc
   add(){
        echo $(expr $1 + $2)
    }

Now edit a file in vim

add 1 5         


        
相关标签:
5条回答
  • 2021-01-04 06:06

    I suppose this should solve it for you. It's more of a workaround than an explanation of you problem but it gets the job done

    :execute '! source ~/.bashrc; source '.expand('%:p')
    

    I'm just manually sourcing bashrc before calling the command. One possible explanation to your problem is if you are on a mac. As far as I know OSX don't source bashrc, they do source bash_profile though.

    0 讨论(0)
  • 2021-01-04 06:08

    To add the line export -f add in .bashrc file.

       add(){
            echo $(expr $1 + $2)
        }
        export -f add
    

    Now source .bashrc,every method can call add function from .bashrc properly.

    0 讨论(0)
  • 2021-01-04 06:17

    How to make both two lines be executed?

     ls
     add 5 6    
    

    This also works (with either shellcmdflag=-ic or shellcmdflag=-c) :

    :w !bash -i
    

    With this approach there is no need to include export -f add in .bashrc.

    Why add function can't be called from vim with !bash %?

    Assuming you have flags shellcmdflag=-c you can do:

    :!bash -i ./%
    

    which is quite similar to the answer of exe.

    0 讨论(0)
  • 2021-01-04 06:22

    The problem is that Vim by default invokes a non-interactive shell, and .bashrc (where you've defined your add function) is only read for interactive shells.

    You can instruct Vim to use an interactive shell:

    :set shellcmdflag=-ic
    

    This may make external command invocations slighly slower (due to the overhead in evaluating your Bash initializations).

    Alternatively, you could define the function somewhere else, so it's always available (but there's no easy place like this; see man bash, esp. the INVOCATION section). Or turn the function into a separate script accessible from your PATH (e.g. ~/bin/add).

    0 讨论(0)
  • 2021-01-04 06:25

    The problem is your function is limited to an interactive shell to execute it you have to do like this

    :!bash -ic "add 1 2"
    
    0 讨论(0)
提交回复
热议问题