2014-11-08 120 views
1

我想指望通過這個循環如何將grep輸出存儲到循環內的變量中?

cd /System/Library/Extensions 
find *.kext -prune -type d | while read d; do 
    codesign -v "$d" 2>&1 | grep "invalid signature" 
done 

我如何可以存儲或計算的輸出產生的輸出是多少?如果嘗試與數組,計數器等,但似乎我無法得到任何東西之外的任何循環。

+0

您需要的數量爲每'協同設計-v「$ d」 2>&1'或整體while循環的次數? – nu11p01n73R 2014-11-08 10:59:35

回答

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

現在,如果你需要計算grep輸出的數量在while循環的每次迭代中的-c選項的輸出grep將是有用的。

cd /System/Library/Extensions 
find *.kext -prune -type d | while read d; do 
    codesign -v "$d" 2>&1 | grep -c "invalid signature" 
done 
  • -c禁止正常輸出;而是爲每個輸入文件打印一條匹配行
+0

非常感謝! wc -l命令完成了任務。我最終改變了兩件事:1)在「wc -l」之後添加了「| tr -d''」,以刪除出現在輸出中的一對不需要的空格。 2)我通過包裝代碼將結果存儲在變量中,如下所示:output = $(code) – DavidD 2014-11-09 08:52:19

+0

@DavidD歡迎您隨時:)很高興知道我有些幫助 – nu11p01n73R 2014-11-09 10:17:24

1

subshel​​l中的經典難點是將變量傳遞回來。

這裏一個方式來獲得這些信息反饋:

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 
相關問題