views:

627

answers:

5

Is it possible to combine redirecting output to a file and pipes with ||? (Not sure what this is called)

Example:

(wget -qO- example.com/duff || exit) | some_processing >> outfile.txt

If wget fails, I would like to exit and not run some_processing or create the blank file.

+1  A: 

|| is a logical or. Not creating outfile.txt would take much more complex syntax; as you have it written (the normal way), outfile.txt is created even before wget is run.

I can't honestly think of any way to force the pipe not to happen at all if the left-hand command fails. I'd just write a Perl script if I were you.

chaos
+2  A: 
#!/bin/bash

RESULT=`wget -qO- example.com/duff`

if [ $? -eq 0 ];
then
  echo $RESULT | some_processing >> outfile.txt
fi
Sean Bright
That did the trick, thanks.
A: 

I think you pretty much answer how to do it.

If wget fails, I would like to exit and not run some_processing or create the blank file.


wget wget -qO- example.com/duff

if [[ $? -ne 0 ]] //$? means return value, on well written programs this should be zero

then

some_processing >> outfile.txt

fi


I think this will accomplish what you want.

Freddy
+1  A: 

([ $? -eq 0 ] && some_processing >> outfile.txt) <<< $(wget -qO- example.com/duff)

nicerobot
A: 

Note that it may not be enough to check for return code. it might be good to also check for return HTTP status such as 404 ..... etc

ghostdog74