繁体   English   中英

基于bash中的循环操作退出带有错误代码的脚本

[英]Exit script with error code based on loop operations in bash

我有一个 CI 管道的包装器脚本,它运行良好,但它总是返回 0,即使 for 循环中的子命令失败。 下面是一个例子:

#!/bin/bash

file_list=("file1 file2 file_nonexistant file3")

for file in $file_list
do
  cat $file
done
>./listfiles.sh
file1 contents
file2 contents
cat: file_nonexistant: No such file or directory
file3 contents
>echo $?
>0

由于循环的最后一次迭代成功,整个脚本以 0 退出。我想要的是循环继续失败,如果任何循环迭代返回错误,脚本退出 1。

到目前为止我尝试过的:

  • set -e但它会在迭代失败时停止循环并退出
  • done || exit 1代替done done || exit 1 - 没有效果
  • cat $file || continue替换cat $file cat $file || continue - 没有效果

备选方案 1

#!/bin/bash

for i in `seq 1 6`; do
    if test $i == 4; then
        z=1
    fi
done
if [[ $z == 1 ]]; then
  exit 1
fi

带文件

#!/bin/bash

touch ab c d e
for i in a b c d e; do
    cat $i
    if [[ $? -ne 0 ]]; then
        fail=1
    fi
done

if [[ $fail == 1 ]]; then
    exit 1
fi

特殊参数$? 保存最后一个命令的退出值。 大于 0 的值表示失败。 所以只需将它存储在一个变量中并在循环后检查它。

美元? 参数实际上保存了前一个管道的退出状态(如果存在)。 如果命令被信号杀死,那么 $? 将是 128+SIGNAL。 例如 128+2 在 SIGINT (ctrl+c) 的情况下。

带陷阱的过度杀伤解决方案

#!/bin/bash

trap ' echo X $FAIL; [[ $FAIL -eq 1 ]] && exit 22 ' EXIT

touch ab c d e
for i in  c d e a b; do
    cat $i || export FAIL=1
    echo F $FAIL
done

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM