代码之家  ›  专栏  ›  技术社区  ›  Mugen

根据命令链中的条件在中间命令中退出

  •  0
  • Mugen  · 技术社区  · 6 年前

    bash

    cmd_1 && \
    cmd_2 && \
    cmd_3 && \
    ...
    cmd_k && \
    ...
    cmd_n
    

    如果这些命令中的任何一个失败,我希望整个链都失败。我在默认的shell行为中得到了它。但是,我想特别允许 cmd_k exit 0

    我试着用

    ...
    (cmd_k || exit 0) && \
    ...
    

    我之所以使用链是因为运行单个docker的环境限制 run 没有任何脚本文件的命令。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Léa Gris    6 年前

    the Docker's run command documentation:

    docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

    您可以通过调用内联shell脚本来运行一系列命令。

    bash 作为 [COMMAND] ,和 -c 'inline script' 作为 [ARG...]

    例子:

    docker run --health-cmd image_foo bash -c 'cmd_1; cmd_2; ...; cmd_j; cmd_k; :'
    

    : exit 0 ).

    作为一个简单的逻辑问题,运行一系列命令并退出 退出0

    #!/usr/bin/env bash
    
    # With if, then
    if ! { true && true && true && true; }; then
      exit 0 # will not exit
    fi
    
    if ! { true && true &&  && false; }; then
      exit 0 # will exit
    fi
    
    if ! true || ! true || ! true || ! true; then
      exit 0 # will not exit
    fi
    
    if ! true || ! false || ! true || ! true; then
      exit 0 # will exit
    fi
    
    # With logic operators only
    ! { true && true && true && true; } && exit 0 # will not exit
    
    ! { false && true && true && true; } && exit 0 # will exit
    
    { ! true || ! true || ! true || ! true; } && exit 0 # will not exit
    
    { ! true || ! true || ! false || ! true; } && exit 0 # will exit
    

    true false

    带有错误陷阱的其他解决方案:

    #!/usr/bin/env bash
    
    trap 'exit 0' ERR # exit 0 on an error
    
    true # successful command
    true # successful command
    true # successful command
    false # will trigger the ERR trap and exit 0
    true # successful command
    true # successful command
    

    实施示例:

    #!/usr/bin/env bash
    
    i=0
    ! {
        { echo $((++i)); true; } &&
        { echo $((++i)); true; } &&
        { echo $((++i)); false; } && # Will stop here at i=3
        { echo $((++i)); true; } &&
        { echo $((++i)); true; }
      } && exit 0
    

    输出:

    1
    2
    3
    
        2
  •  1
  •   tripleee    6 年前
    (cmd_k || exit 0) && true
    

    exit true . 如果你不在乎 cmd_k 不管成功与否,你只要

    cmd_k; true