如何在批处理脚本中检查grep是否匹配?

时间:2015-03-05 19:39:46

标签: bash

在Ubuntu上的静态存档文件列表中,我需要获取定义函数的特定存档。这是我放在一起的脚本:

for line in `find . -iname '*\.a'`; do
 nm $line 2>/dev/null | grep -H "T $1"
done

问题是grep正在输入标准输入。我想知道是否有办法检查grep是否成功,如果有,则显示文件名。或者,可能有更好的方法来实现我想要的。问候。

2 个答案:

答案 0 :(得分:2)

#!/bin/bash
# Use recursive globs to find files. This avoids problems with special chars.
shopt -s globstar nullglob
for file in ./**/*.[aA]
do
  # Ignore grep output and instead check its return code
  if nm "$file" 2> /dev/null | grep -q "T $1"
  then
    echo "$file matches"
  fi
done

以下是一个示例运行:

/home/me $ cd /usr/lib
/usr/lib $ myscript __sha512_init_ctx
./x86_64-linux-gnu/libcrypt.a matches
/usr/lib $

答案 1 :(得分:1)

for line in `find . -iname '*\.a'`; do
  nm $line 2>/dev/null | grep -H "T $1"
  [[ $PIPESTATUS[1] -eq 0 ]] && echo $line
done

来自bash的联系方式:

PIPESTATUS
       An array variable (see Arrays below) containing a list
       of exit status values from the processes in the
       most-recently-executed foreground pipeline (which may
       contain only a single command).