Loops 在循环外部读取行循环迭代计数器时使用sh
我正在编写git钩子,对下一个代码行为感到非常困惑:Loops 在循环外部读取行循环迭代计数器时使用sh,loops,counter,sh,arithmetic-expressions,Loops,Counter,Sh,Arithmetic Expressions,我正在编写git钩子,对下一个代码行为感到非常困惑: #!/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
#!/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。我的错误在哪里?这是因为管道是在不同的进程中执行的。只需将其替换为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