I need to create a program in Bash that launches a command, check if the result contain a word, and do something if it does.

Example: I need to check if a printer is online with

lpstat -p [printer name]

and if the result contains the word inactive the script should send me a mail.

How can I check a program's output for a word?

1 Answer 1


This is a task for the mighty grep.

lpstat -p myprinter | grep inactive

will connect the output of lpstat to the input of grep, which will then print those lines that contain the string inactive.

To print the lines that contain the word inactive (i.e., inactive surrounded by spaces, commas and the like), you can add an option:

lpstat -p myprinter | grep -w inactive

However, you want to perform a test. You need to know that grep will generate an exit value of "success" (actually, it's a 0) whenever it does find the word. This can be used for testing. You are also not interested in the output of the grep command, just the success status. Let's therefore ask grep to be quiet, and wrap a test around it:

if lpstat -p myprinter | grep -q -w inactive
    mail -s "printer is inactive" othin

Here is your reading assignment: https://www.man7.org/linux/man-pages/man1/grep.1.html.

  • thank you very much bernbausch! i'll try now
    – Othin
    Jul 29, 2021 at 8:04
  • @Othin if you found the answer useful, please consider accepting it so that others facing a similar issue may find it more easily.
    – AdminBee
    Jul 29, 2021 at 9:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .