我想计算此循环产生的输出数量
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep "invalid signature"
done
如何存储或计算输出?如果尝试使用数组,计数器等,但似乎我无法获得该循环之外的任何内容。
答案 0 :(得分:3)
要获得while循环产生的行数,可以使用wc
字数
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep "invalid signature"
done | wc -l
wc -l
-l选项计算输入中的行数,通过管道输出到while
的输出现在,如果您需要在while循环的每次迭代中计算grep
输出的数量,-c
的{{1}}选项将非常有用。
grep
cd /System/Library/Extensions
find *.kext -prune -type d | while read d; do
codesign -v "$d" 2>&1 | grep -c "invalid signature"
done
抑制正常输出;而是打印匹配行的计数
对于每个输入文件答案 1 :(得分:1)
这里有一种获取此信息的方法:
cd /System/Library/Extensions
RESULT=$(find *.kext -prune -type d | {
# we are in a sub-subshell ...
GCOUNT=0
DIRCOUNT=0
FAILDIR=0
while read d; do
COUNT=$(codesign -v "$d" 2>&1 | grep -c "invalid signature")
if [[ -n $COUNT ]]
then
if [[ $COUNT > 0 ]]
then
echo "[ERROR] $COUNT invalid signature found in $d" >&2
GCOUNT=$(( $GCOUNT + $COUNT ))
FAILDIR=$(( $FAILDIR + 1 ))
fi
else
echo "[ERROR] wrong invalid signature count for $d" >&2
fi
DIRCOUNT=$(( $DIRCOUNT + 1 ))
done
# this is the actual result, that's why all other output of this subshell are redirected
echo "$DIRCOUNT $FAILDIR $GCOUNT"
})
# parse result integers separated by a space.
if [[ $RESULT =~ ([0-9]+)\ ([0-9]+)\ ([0-9]+) ]]
then
DIRCOUNT=${BASH_REMATCH[1]}
FAILDIR=${BASH_REMATCH[2]}
COUNT=${BASH_REMATCH[3]}
else
echo "[ERROR] Invalid result format. Please check your script $0" >&2
fi
if [[ -n $COUNT ]]
then
echo "$COUNT errors found in $FAILDIR/$DIRCOUNT directories"
fi