On Thu, 22 Aug 2002, Randy Kramer wrote:

> I'm a newbie trying to create a bash script.  (I'm not sure whether this is a 
> "newbie level" question or not.)
> 
> I'd like to run a command (almost anything) in an if statement and direct 
> it's normal output to standard out but also test that output using grep to 
> use the result in the logic of the script.

There are several approaches you could take, all depending on the length
of output and what else you'd need to do with it. One approach that
you've found is to redirect the output to a temporary file:

  somecommand > tmpfile.$$

The $$ expands to the process ID of the command and is useful for
quickly generating a filename. You can then parse the file with sed,
awk, or whatever you need.

> 
> For example, the output of mailq is "Mail queue is empty" if the mail queue 
> is empty, and a list of messages if there are any in the queue.
> 
> In butchered pseudocode, I'd like to do something like this:
> 
>    * run mailq displaying output
>    * if mailq was empty (tested like: mailq | grep -c "empty") 
>          do something
>      else
>          do something else
>      fi
> 
> I could do something like run mailq and capture the output in a file or 
> variable, then:
>    * print the file or variable
>    * test the file or variable
> 
> Or, I could run the command twice, but I want to avoid that.

Yes, definitely avoid this. The output may change between runs.
> 
> I thought there might be an easier way (or a one liner type approach, which 
> while it might be one line might be fairly difficult (for me) to understand 
> ;-)

Look through the bash conditional operators. There's a ?: operator that
may do what you need. 
> 
> I've started trying variations of the following, but I'm really just shooting 
> in the dark:
> 
> if mailq tee grep -c "empty"
> 

You're missing the pipe '|' between commands.

> Randy Kramer
> 
> 


Want to buy your Pack or Services from MandrakeSoft? 
Go to http://www.mandrakestore.com

Reply via email to