+ -
当前位置:首页 → 问答吧 → 为什么在这种情况下, ERR信号不能捕捉到?

为什么在这种情况下, ERR信号不能捕捉到?

时间:2011-06-17

来源:互联网

  1. #!/bin/bash

  2. set -o pipefail
  3. set -E

  4. trap 'echo "ERR CATCHED in  LINE: ${LINENO}"' ERR

  5. ls FILE_NOT_EXIST_00

  6. [b]ls FILE_NOT_EXIST_01  | while read LINE ; do
  7.         echo "in while: $LINE"
  8. done[/b]

  9. ls FILE_NOT_EXIST_02 | head

  10. exit 0
复制代码
执行的输出结果是:
  1. ls: cannot access FILE_NOT_EXIST_00: No such file or directory
  2. ERR CATCHED in  LINE: 8
  3. ls: cannot access FILE_NOT_EXIST_01: No such file or directory
  4. ls: cannot access FILE_NOT_EXIST_02: No such file or directory
  5. ERR CATCHED in  LINE: 15
复制代码
ls FILE_NOT_EXIST_01  | while read LINE ;  这个错误没有被捕捉到...  有点奇怪!
我的bash版本是“GNU bash, version 3.2.33(1)-release (i386-redhat-linux-gnu)”

作者: binary_XY.Z   发布时间: 2011-06-17

ls FILE_NOT_EXIST_01 2>&1 | while read LINE

作者: ly5066113   发布时间: 2011-06-17



QUOTE:
ls FILE_NOT_EXIST_01 2>&1 | while read LINE
ly5066113 发表于 2011-06-17 15:18




    一样哦, 我的意思是问: 为什么在 ls FILE_NOT_EXIST_01 |  while  这种情况下,   ls 产生的错误没有被  trap  ''  ERR 捕捉到~~

作者: binary_XY.Z   发布时间: 2011-06-17

回复 binary_XY.Z


哦,原来是这个意思。
没具体研究过 trap ,但估计是因为管道起了子shell的关系。

作者: ly5066113   发布时间: 2011-06-17



QUOTE:
回复  binary_XY.Z


哦,原来是这个意思。
没具体研究过 trap ,但估计是因为管道起了子shell的关系。 ...
ly5066113 发表于 2011-06-17 15:23




    嗯, 估计是跟sub-shell有关系...  所以我在开头加了 set -E来让错误捕捉也可以继承到sub-shell , 但是在ls FILE_NO_EXIST | while 情况下, ls 产生的错误却不能被捕捉到了, 真是诡异啊..

作者: binary_XY.Z   发布时间: 2011-06-17