Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call bash function using vim external command

Tags:

bash

vim

I use vim's :! external command function all the time, usually providing % as an argument to the shell command. For example :

:!psql -f %

I also have a lot of bash shell functions in my .bashrc that I use. For example:

psql-h1 () 
{ 
    /usr/bin/psql -hh1 -d mydb "$@"
}

These bash functions aren't available from :! inside of vim. Is there a way to make them available?

like image 334
Jeremy Avatar asked Oct 25 '17 17:10

Jeremy


People also ask

Can I call bash function from command line?

Finally you just have to add the source ~/bin/functions.sh line to your . bashrc file. This way you will be able to call them from the command line, your . bashrc will stay clean, and you will have a specific place for your personal functions.

How do I execute a function in bash?

To invoke a bash function, simply use the function name. Commands between the curly braces are executed whenever the function is called in the shell script. The function definition must be placed before any calls to the function.

How do you write and call a function in bash?

Creating a Function in Bash The code between the curly braces {} is the function body and scope. When calling a function, we just use the function name from anywhere in the bash script. The function must be defined before it can be used.


2 Answers

Export your functions. That is:

psql-h1() { /usr/bin/psql -hh1 -d mydb "$@"; }

export -f psql-h1  ### <-- THIS RIGHT HERE

This will make them available to any copy of bash run as a child process, even if it's a noninteractive shell and so doesn't read .bashrc.

like image 152
Charles Duffy Avatar answered Sep 28 '22 19:09

Charles Duffy


An alternative to exporting your functions (which may no reach Vim is there's a non-Bash shell in between; see here for such a case), you can instruct Vim to start an interactive shell, so that your .bashrc is read. Just pass the -i flag to Bash, via Vim's :help 'shellcmdflag'.

:set shcf=-ic
like image 37
Ingo Karkat Avatar answered Sep 28 '22 20:09

Ingo Karkat