Redirecting Grep Error Output to a File

grepoutputstderr

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.

Best Answer

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

Related Question