Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Is there something you can type into terminal so that it will run a command if a certain program is running? For example, if <Libre office is running> then sudo pkill <Libre ofice>.

Edit 1: So what I want to do is make an if statement in terminal that runs if a program is running and if it is not it does nothing, or does something else.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

"what I want to do is make an if statement in terminal that runs if a program is running and if it is not it does nothing, or does something else"

To determine if a program is running given its name, use pgrep. To dosomething if LibreOffice's word processor is running:

pgrep soffice.bin >/dev/null && do_something

Similarly, to do something if LibreOffice's word processor is not running:

pgrep soffice.bin >/dev/null || do_something

Further, you can use these two in combination:

pgrep soffice.bin && do_one_thing || do_another

Or, if things get more complicated, use an if statement:

if pgrep soffice.bin
then
    # command is running
    do_one_thing
    do_one_thing2
else
    # command is not running
    do_another
    do_another2
fi

The above work because pgrep, just like grep, sets a useful exit code. If a process is found, it returns with an exit code of zero (which the shell interprets as logical true). If not, it returns with one (the shell interprets any non-zero exit code to mean false).

To find out all the programs that are currently running (and hence what name to use as the argument to pgrep), run ps ax

share|improve this answer
    
Was just about to answer almost the same thing. You might want to add the combination of the two into one: pgrep soffice && do_one_thing || do_another –  mtmiller May 5 at 23:26
    
@mtmiller Thanks. I add that to the answer. –  John1024 May 5 at 23:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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