0

I have few commands linked through pipes, and at the end is a conditional awk: example below

command1 | command 2 | awk '$1 > 800'

Now sometimes it will output few lines, and sometimes no lines. I want a condition that will prove true only if there's some output (1 or more lines) Is there a way to make it work?

Like,

if command1 | command 2 | awk '$1 > 800' (some output); then
do command3
else; (blank output)
Do nothing
1
  • You could pipe the output into a while read construct. The while loop will iterate once for every line of output. Is that what you are looking for? Commented Nov 14, 2018 at 11:45

3 Answers 3

3

I normally just use command substitution, then put it in a test, e.g.

if [ ! -z "$(command1 | command 2 | awk '$1 > 800')" ]; then command3; fi

Explanation

  • This runs the command as per your question: command1 | command 2 | awk '$1 > 800'
  • The output of this is passed to the test [ ! -z "$(…)" ], which will be true if it is not ! a string of zero length -z.

Hence, if there is output to the command pipe, the then commands will run.

1
  • Thanks @Sparhawk that is exactly what I was looking for. Commented Nov 14, 2018 at 12:11
1

Make the awk script exit with the correct return code for your if statement:

if command1 | command2 | awk '$1 > 800 { c++; print } END { exit (c == 0) }'
then
   command3
fi

Or, if you don't actually need the output of the awk program:

if command1 | command2 | awk '$1 > 800 { c++; exit } END { exit (c == 0) }'
then
   command3
fi
4
  • Could c wrap (or is awk arbitrary precision)? Commented Nov 14, 2018 at 13:03
  • Note that that exit would close the pipe and potentially cause command2 to be killed with SIGPIPE (which may or may not be desired) Commented Nov 14, 2018 at 13:11
  • @ctrl-alt-delor, awk typically uses long C compiler type for its integers which will generally be 64bit. It would take years for that number to wrap. Commented Nov 14, 2018 at 13:14
  • My computer can do in a month, what would have taken millions of years in 1970. So if Mores law continues, millions of years is less than 50 years away. Commented Nov 14, 2018 at 13:18
0

You can let awk print the desired exit code, like this:

echo 900 | awk '{ print !($1 > 800) }'

Then this can be wrapped in a subshell using ( and exit, for returning the value from awk:

echo 900 | (exit $(awk '{ print !($1 > 800) }'))

Which can then be used as part of a pipeline:

echo 900 | (exit $(awk '{ print !($1 > 800) }')) && echo yes || echo no

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.