Error redirection question

Hi gurus,
I have a question, need some of your inputs...

I have a command like this :

export LINE_COUNT=`wc -l test.dat | awk '{print $1}'`

echo $LINE_COUNT         --- > gives me 2 which is fine as the file has 2 lines.

This works fine if the file test.dat is present but in case test.dat is not present (I intentionally remove the file), I want to redirect only the error to a specified error file like say test.err. For that I tried to do the following:

export LINE_COUNT=`wc -l test.dat | awk '{print $1}'` 2> test.err

I still got the error as "wc: cannot open test.dat" at the command promprt and the file test.err was empty.

I also tried :

export LINE_COUNT=`wc -l test.dat | awk '{print $1}' 2> test.err`

and I still got the error as "wc: cannot open test.dat" at the command promprt and the file test.err was empty.

My intention is only to redirect the error part of my command to a specific file say test.err and not display at the command prompt.

Hope I was clear.
Thanks for your time,
Carl

Standard error doesn't pass through pipes. It goes directly to the terminal. So redirecting the last command only redirects errors the last program prints.

command 2> errlog | command2 | command3

It's extremely wasteful to run awk to process single lines. Might be better to do this:

[ -r test.dat ] && export LINE_COUNT=`wc -l < test.dat` || echo "Can't read test.dat" >&2

Faster since it uses less processes, and the error messages can be whatever you'd like.

1 Like

Redirect output of wc to test.err instead of the awk part...

export LINE_COUNT=`wc -l test.dat 2>test.err | awk '{print $1}'`
1 Like

Thank you v.much for your inputs... certainly it works.