Using a vim function, I would like to check if a program is running using pgrep, and if it is not running then do something. In particular, I want to achieve something like this:

function! checkifrunning(mystring)
    if 'pgrep "mystring"' shows that something is NOT running
        --do something--

My guess is that I need to use the 'system()' function, but I'm not sure how. Can somebody help?

EDIT: I would like a solution that uses pgrep in particular, and not some other way

  • 1
    If you're interested in Vim, do check out sister site Vi and Vim. – muru Jun 23 '16 at 6:54
function! checkifrunning(mystring)
    if !system('pgrep "' . a:mystring . '"')
        " --do something--

Technically ! operates on Numbers, and converts a String to a Number first if given a String. However, if there's no process running, the output of pgrep will be empty, which when converted to a Number is 0. If there are process running, conversion to a Number would give non-zero.

Instead of 'pgrep "' . a:mystring . '"', you could also do 'pgrep ' . shellescape(a:mystring).


You can use like

:call system("pgrep process name ")

To print the output ,

:echo system("pgrep process name ")

You can store the output in a variable like

:let a=system("pgrep process name ")

And, use that variable in any loop, print, or use string functions as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.