Temporary redirection of stderr in a bash script

送分小仙女□ 提交于 2019-12-10 15:44:38

问题


I have a simple script which is used to start another program. This other program may sometimes yield a SIGSEGV, which disrupts my output. I have therefore added a couple of lines which is supposed to temporarily redirect the stderr to /dev/null such that the SIGSEGV is ignored. The following is a draft of my code:

exec 2> /dev/null
progname >& ./tmp/run.txt && run_status='OK'
exec 2>1

The problem is that the last line does not do what I want. The first line obviously works, and redirects the stderr. The last line is supposed to return the stderr back to where it was before (which I have only supposed is the same as stdout).

Any help would be appriciated!


回答1:


Another option is:

exec 3> /dev/stderr 2> /dev/null
progname >& ./tmp/run.txt && run_status='OK'
exec 2>&3

Or even

exec 3>&2 2> /dev/null
progname >& ./tmp/run.txt && run_status='OK'
exec 2>&3

That way the script preserves the separation of stdout and stderr for the script (ie. the scripts stdout and stderr can be redirected separately.




回答2:


Why not just redirect it for the progname run only?

   progname > ./tmp/run.txt 2>/dev/null && run_status='OK'

Or possibly

{
   progname > ./tmp/run.txt && run_status='OK'
} 2>/dev/null


来源:https://stackoverflow.com/questions/447101/temporary-redirection-of-stderr-in-a-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!