Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

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

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

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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 $(...).

share|improve this answer
    
devnull, thank you! you're the best. thank you very much! :) –  user60216 Mar 1 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
share|improve this answer
    
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 at 5:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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