1

I've got a unix command sequence that goes something like:

command1 | command2 | command3 | wc -l

Now that I have the number of lines, I'd like to do something (run a specific command with no inputs) if the number of lines isn't equal to a specific number. My shell scripting is fantastically rusty (perhaps 10 years or more since I've done much Unix work) so I don't know how to add this kind of conditional to a command sequence. Does anyone know?

quillbreaker
  • 6,119
  • 3
  • 29
  • 47

3 Answers3

5

You need to capture the output of your wc command and use if to run another command if it's not equal to the number of lines you want, such as:

count=$(command1 | command2 | command3 | wc -l)
if [[ $count -ne 19 ]] ; then
    command4
fi
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3
numberOfLines=$(command1 | command2 | command3 | wc -l)
if [ "${numberOfLines}" == "7" ]; then
    echo "Hooray."
fi
Bombe
  • 81,643
  • 20
  • 123
  • 127
2

Kinda ugly .. but this works.

#  test $(seq 10 | wc -l) -eq 10 && echo "there's 10"
there's 10
#  test $(seq 11 | wc -l) -eq 10 && echo "there's 10"

nothing's echoed in the second case

eduffy
  • 39,140
  • 13
  • 95
  • 92
  • that reminds me of my college days, when our unix programming instructor advised us not to name our compiled programs "test". – quillbreaker Aug 25 '09 at 15:05
  • seems I need backticks instead of $() syntax for csh, but otherwise this works great. thanks. – quillbreaker Aug 25 '09 at 16:32
  • 1
    You named them? .. I was happy with `a.out` :p – eduffy Aug 25 '09 at 20:43
  • 2
    Now I want a time machine, to get to someone's terminal back in college and add a command to a directory in their path called "a.out" that only sleeps for 2 seconds and prints "core dump". – quillbreaker Sep 25 '09 at 17:17