set -e and short tests

前端 未结 4 783
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-23 10:17

When I was new to shell scripting, I used a lot of short tests instead of if statements, like false && true.

Then later I learned u

4条回答
  •  攒了一身酷
    2020-12-23 11:09

    You need to end each command which may fail with || and a command or command list evaluating to 0. Using || will trigger your command if the expression before operator does not evaluate to 0. Your command needs to evaluate to 0 to not kill the shell.

    Example:

    set -e
    false || true # silently ignore error
    
    false || echo "Command failed, but exit status of echo is 0. Continuing..."
    
    false || {                                                                      
      echo "Command failed. Continuing..."                                          
      # do something else                                                           
      false && true # all commands in the list need to be true                      
    }
    

    false && true does not cause an exit because ending expression is evaluated and evaluates to 0. From the bash man page for set -e:

    Exit immediately if a pipeline (which may consist of a single simple command), a subshell command enclosed in parentheses, or one of the commands executed as part of a command list enclosed by braces (see SHELL GRAMMAR above) exits with a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command's return value is being inverted with !. A trap on ERR, if set, is executed before the shell exits. This option applies to the shell environment and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before executing all the commands in the subshell.

    Only last command if executed in ||/&& chain can trigger exit.

    The following expression will fail from the reason above.

    true && false
    

    but the following will not:

    if true && false                                                                
    then                                                                            
      true                                                                          
    fi                   
    

    because of true && false is part of test following if.

提交回复
热议问题