当前位置: 动力学知识库 > 问答 > 编程问答 >

linux - Hide stderr and pipe stdout in tcsh

问题描述:

How can I hide stderr but use stdout in csh script?

I'm trying to find occurrences in some file which may exist or not, and act according to the result:

if (`grep phrase file | wc -l` > 0) then

echo 'Match!'

endif

The problem is that if the file does not exist an error is shown on the console.

I found how to drop stderr and redirect stdout to console (according to http://unix.stackexchange.com/questions/35715/stderr-redirection-not-working-in-csh):

`(grep phrase file | wc -l > /dev/tty) >& /dev/null

But it doesn't work in my case because I want to use the result in the script.

I thought about replacing /dev/tty in a temporary file and use its content, but I wonder if there is a solution without temporary file.

Another way is to use bash from my csh script:

if (`echo 'grep phrase file 2> /dev/null' | sh | wc -l`) then

echo 'Match!'

endif

But this may complicate the script if the grep command is more complex, e.g. when using variable the below command is not going to work as-is:

if (`echo 'grep $phrase file 2> /dev/null' | sh | wc -l`) then

echo 'Match!'

endif

Thus I prefer csh pure solution.

How can I do that in pure csh?

网友答案:

You can close standard error by just suffixing 2>&- to the command.

If C shell (in particular) complains about that syntax (I don't honestly recall, and I don't see it in the surprisingly incomplete "reference manual"), then do it by the old Swiss army knife technique, that is, 2>/dev/null. That's what /dev/null is there for: it's an entry point into the memory device driver that merely discards the data written to it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: