首页 文章

在tcsh中隐藏stderr和pipe stdout

提问于
浏览
1

如何隐藏stderr但在csh脚本中使用stdout?

我试图在某个文件中找到可能存在或不存在的事件,并根据结果执行操作:

if (`grep phrase file | wc -l` > 0) then
    echo 'Match!'
endif

问题是如果文件不存在,控制台上会显示错误 .

我发现如何删除stderr并将stdout重定向到控制台(根据https://unix.stackexchange.com/questions/35715/stderr-redirection-not-working-in-csh):

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

但它在我的情况下不起作用,因为我想在脚本中使用结果 .

我想在一个临时文件中替换 /dev/tty 并使用它的内容,但我想知道是否有没有临时文件的解决方案 .

另一种方法是使用我的csh脚本中的bash:

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

但是如果grep命令更复杂,例如,这可能会使脚本复杂化 . 当使用变量时,下面的命令不会按原样运行:

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

因此我更喜欢csh纯解决方案 .

我怎么能用纯csh做到这一点?

1 回答

  • 1

    您只需将 2>&- 后缀添加到命令即可关闭标准错误 .

    如果C shell(特别是)抱怨这种语法(我不会在令人惊讶的不完整_1366823中看到它),那么就用旧的瑞士军刀技术,即 2>/dev/null 来做 . 那个's what /dev/null is there for: it'是内存设备驱动程序的入口点,它只丢弃写入它的数据 .

相关问题