避免脚本中的重复

问题描述 投票:0回答:1

下面的代码在完整脚本中重复了两次,如何避免?

        if jurge_expr ; then
            (( retry_cnt += 1 ))
            echo $CS2
            echo "reading CS2 checking failed. retry, retry_cnt=$retry_cnt"
            if [[ $retry_cnt -gt $max_retry_cnt ]]; then
                echo "$RED retry too many times, failed to write 0xe2 $bytes 2 $filename $RESET"
                break;
            fi
            sleep 0.5
            continue;
        fi

这是完整的脚本:

# Loop through each filename in sorted_files and print it
set -- $sorted_files
for filename; do
    addr=$(echo "$filename" | cut -d_ -f1)
    bytes=$(echo "$filename" | cut -d_ -f2 | sed -e 's/B.dat//' -e 's/KB.dat//')
    
    retry_cnt=0;
    while true; 
    do
        echo "bulk writing 0xe2 $bytes 2 $filename"
        ccidbgr /dev/cci2 0x6d bulkWrite 0xe2 $bytes 2 $filename
        sleep 0.5
        echo "reading CS2"
        CS2=$(ccidbgr /dev/cci2 0x6d read 0xF2 2>&1)
        if [[ $? -ne 0 ]]; then
            (( retry_cnt += 1 ))
            echo $CS2
            echo "reading CS2 checking failed. retry, retry_cnt=$retry_cnt"
            if [[ $retry_cnt -gt $max_retry_cnt ]]; then
                echo "$RED retry too many times, failed to write 0xe2 $bytes 2 $filename $RESET"
                break;
            fi
            sleep 0.5
            continue;
        fi
        
        echo $CS2
        CS2=$(echo $CS2 | cut -dx -f3)
        if [[ $CS2 -eq 0 ]]; then
            (( retry_cnt += 1 ))
            echo "read CS2 is zero. retry, retry_cnt=$retry_cnt"
                if [[ $retry_cnt -gt $max_retry_cnt ]]; then
                echo "$RED retry too many times, failed to write 0xe2 $bytes 2 $filename $RESET"
                break;
            fi
            sleep 0.5
            continue;
        fi
    done
done

shell ksh
1个回答
0
投票

功能?考虑一下:

...
fun(){
    (( retry_cnt += 1 ))
    echo $CS2
    echo "reading CS2 checking failed. retry, retry_cnt=$retry_cnt"
    if [[ $retry_cnt -gt $max_retry_cnt ]]; then
        echo "$RED retry too many times, failed to write 0xe2 $bytes 2 $filename $RESET"
        break;
    fi
    sleep 0.5
    continue
}
...
[[ $? -ne 0 ]] && fun
...
[[ $CS2 -eq 0 ]] && fun
...
© www.soinside.com 2019 - 2024. All rights reserved.