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.

For example I want to execute :

ps x | grep something | grep -v grep | somecommand

I want to execute somecommand only if there is something running. How to do that ?

share|improve this question
add comment

3 Answers

Here is the solution

ps x | grep something | [[-n $(grep -v grep) ]] && somecommand

  • -n will check whether string is null or not
  • && is and operator
share|improve this answer
add comment

This is simple:

pgrep something && somecommand

pgrep is like ps | grep something | grep -v grep, terser but with less options to control output. However, you don't have to worry that you filter out by chance something that actually is needed (e.g. pgrep agreppina will work, but ps x | grep agreppina | grep -v grep will not).

command1 && command2 is somewhat like any conjunction in a programming language, command2 will be executed only if first command was successful (actually, if it returned a status of zero).

share|improve this answer
add comment

You can use if. Also, to grep for a command, but to exclude the grep itself, you can use the following trick:

if ps x | grep '[s]omething' ; then
    echo Running.
else
    echo Not running.
fi
share|improve this answer
add comment

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.