I wanted to capture to a file the errors being returned on the command line from grep. For example,

grep foo.lookup
No such file in directory

I want to output that to a log file. This is my shell script:

var1=$(grep $lookUpVal foo.lookup) >>lookup.log 2>$1

It creates the file lookup.log but doesn't write the error on it.


If I understand it correct, you want to capture the output of grep into a variable and append any error to the logfile.

You could say:

var1=$(grep $lookUpVal foo.lookup 2>>lookup.log)

The $(...) syntax denotes command substitution, i.e. outputs the result of the command into a variable. By default it would capture the STDOUT of the command into the variable and the STDERR is printed to the console. In order to redirect the STDERR to a file, you would need to perform the redirection within the command itself, i.e. within $(...).

  • devnull, thank you! you're the best. thank you very much! :) – user60216 Mar 1 '14 at 6:20

grep foo.lookup isn't a correct example. It's missing an argument, either a search parameter or a filename.

To capture just the error messages that grep returns to a file you could do this:

$ grep $lookUpVal foo.lookup 2> errors.log

All errors are sent to STDERR (2>) while all output is sent to STDOUT (1>). They're combined like this:

$ grep $lookUpVal foo.lookup > output.log 2>&1
  • grep foo.lookup is the error message. I want that to be printed in the file. The grep is part of the shell script. It has to return a value to a variable. – user60216 Mar 1 '14 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.