1

I have functions defined in a file that is sourced by my .bashrc file (shown below). The command is found just fine from the bash command line, and also when I execute a subshell and use the command. Within a vim session however, the function foo is not found when I execute a bang command. How do I make the foo function visible to the bang command?

foofile: 

    printf "%s\n" "here I am in foofile"

    function foo () {
        printf "%s\n" "Here I am in function foo.  Love ya ma!"
    }

    export foo

(in vim) 

:!foo
/bin/bash: foo: command not found

shell returned 127
Leonard
  • 13,269
  • 9
  • 45
  • 72
  • 1
    Possible duplicate of [Call bash function using vim external command](https://stackoverflow.com/questions/46939026/call-bash-function-using-vim-external-command) – Michail Mar 29 '19 at 22:33

1 Answers1

2

TL;DR: if you export -f foo in your bashrc, you'll get the functionality you want at the cost of every subshell you make having that function.

vim runs its own shell. This shell does not source your .bashrc.

You can run env -i bash --norc --noprofile to emulate this shell.

This shell still has a minimal $PATH. For something to be executed in this shell, it has to be in that path. You should probably use /usr/local/bin or /usr/bin.

Make a file called foo as follows

#!/bin/bash
someName() {
    #contents of foo from your bashrc
}
someName #someName here can be foo, and you can just copy your whole function, 
#but I wanted to show that this name doesn't have to relate to the fileName

put that file in one of those folders and make it executable (chmod 744 is a decent bet)

EDIT:

If you don't want to make utility functions have their own files, you can simply source your .bashrc as part of your command:

:!source ~/.bashrc && foo

Second EDIT:

Michail pointed out an alternative, which is to have your .bashrc export all functions so that they can be used in subshells.

foo() {
    ....
}
export -f foo

now in vim you can type

:!foo 

and it will work as expected

jeremysprofile
  • 10,028
  • 4
  • 33
  • 53