Key things to know:
- You can call shell commands from Vim using the function
system()
.
- Just like the shell itself you can combine shell commands in the
system()
parameter string by separating them with ;
.
- You can combine multiple Vim commands on a single command line using
|
.
- When you use
|
in a mapping you must escape it as \|
. <bar>
also works.
Putting that all together we get...
noremap <C-W> :w \| call system('notify-send "This is a bash script"; npm install; pm2 restart myservice; randomCommandThatICreate')<CR>
Notice that I'm using :noremap
rather than :map
as you should always use that (and :nnoremap
, :inoremap
, etc.) unless you know for sure that you want remapping of the RHS.
Also, unless you really want to use this mapping in multiple modes it's advisable to use more specific map commands. For instance, this seems like the kind of thing you'd usually call from Normal mode so :nnoremap
might be preferable.
Finally, you might want things to be a bit more manageable/edit-friendly than a single long mapping line. Here's one option...
let g:shellcmds = [
\ 'notify-send "This is a bash script"',
\ 'npm install',
\ 'pm2 restart myservice',
\ 'randomCommandThatICreate']
func RunShellCmds() abort
for l:cmd in g:shellcmds
call system(l:cmd)
endfor
endfunc
noremap <C-W> :w \| call RunShellCmds()<CR>
Or without the function...
noremap <C-W> :w \| for shcmd in g:shellcmds \| call system(shcmd) \| endfor<CR>