6

How do I evaluate or calculate the return value of a command line? For exemple, I count the number of lines with a grep and I want to know if that value is above X. If so, I want to print the number to a file.

Or I want to substract the value of a grep count to another grep count...

How can I manipulate return values that way ?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Philippe Carriere
  • 197
  • 1
  • 1
  • 6

1 Answers1

11

I think you are mixing two things the return value typically indicates if a command was successful (return value 0) or not (anything else). You can get the return value of a command from the variable $?

grep -c returns the count to stdout, to capture the count you can use something like

variable=$(grep -c pattern filename)

Afterwords you can calculate/access the variable how ever you want. See How to do integer & float calculations, in bash or other languages/frameworks? how to calculate stuff with the output.

Ulrich Dangel
  • 25,079
  • 3
  • 80
  • 80
  • Yeah that was what I meant. And your answer is perfect ! – Philippe Carriere Jul 04 '12 at 19:54
  • `$?` is the 8-bit exit status of each program. Values of `0` and `1` have standard definitions. Values `2` through `255` are reserved for the program - it may return more information, check the `man` page for the particular program. Some usages ignore this extra information, and treat `$?` value `0` as Success, anything else as Not-Success (Failure). – waltinator Apr 02 '22 at 18:23