【问题标题】:Use sh while-read-line-loop iteration counter outside loop在循环外使用 sh while-read-line-loop 迭代计数器
【发布时间】:2024-01-08 10:09:01
【问题描述】:

我正在编写 git hook 并且对接下来的代码行为感到非常困惑:

#!/bin/sh

exit_code=0

git diff --cached --name-only --diff-filter=ACM | while read line; do
    echo "Do something with file: $line"
    # some stuff with exit code is equals to 0 or 1
    stuff_exit_code=$?
    exit_code=$(($exit_code + $stuff_exit_code))
done

echo $exit_code
exit $exit_code

我希望 echo $exit_code 会为每个我的东西退出代码非零生成文件总数。但我总是看到 0。我的错误在哪里?

【问题讨论】:

    标签: loops counter sh arithmetic-expressions


    【解决方案1】:

    这是因为管道在不同的进程中执行。只是将它替换为 for-in 循环。

    #!/bin/sh
    
    exit_code=0
    
    for file in `git diff --cached --name-only --diff-filter=ACM`
    do
        echo "Do something with file: $file"
        # some stuff with exit code is equals to 0 or 1
        stuff_exit_code=$?
        exit_code=$(($exit_code + $stuff_exit_code))
    done
    
    echo $exit_code
    exit $exit_code
    

    【讨论】: