Skip to content

Option to abort a script if a command fails (e.g., set -o errexit) #510

Open

Description

@darthdeus

Think of this as an alternative to set -e in bash. What it would do is abort the whole script, if a single line fails.

This is useful in cases like this

import foo
do_some_magic
import bar

in this case you definitely don't want to do_some_magic if import foo fails.

It might also be good to have this option available just for blocks, so that you could do

some_magic

begin -e # or whatever the switch will be
  first_thing  # if this fails, the whole block will exit
  second_thing
end

some_more_magic

Using and is not a solution for more than two commands, as it pollutes the script, makes it harder to refactor, etc.

Activity

  1. JanKanis commented on Jan 12, 2013

    @JanKanis
    Contributor

    +1 on this! Not sure what the interface should look like, a variable $fish_option_exit_on_error maybe?

  2. darthdeus commented on Jan 12, 2013

    @darthdeus
    Author

    For the block it should definitely be another argument to the begin call

  3. JanKanis commented on Jan 12, 2013

    @JanKanis
    Contributor

    A variable would be more in line with other configuration options. I don't think there's any precedence for options to block commands that do anything similar. And the and command can be used with more than two commands, so such a -e switch to begin doesn't buy anything for small blocks at least.

    begin
        first_thing
        and second_thing
        and third_thing
    end
    
  4. nvie commented on Jan 12, 2013

    @nvie
    Contributor

    The begin -e syntax looks great. I'd prefer it over the variable.

  5. danieljames commented on Jan 12, 2013

    @danieljames
    Contributor

    It'd be nice to be able to use it with functions as well, although -e isn't available. I suppose a nested block would work, but would be a bit awkward.

  6. terlar commented on Jan 12, 2013

    @terlar
    Contributor

    +1 for an option to the begin block and also to function

  7. darthdeus commented on Jan 13, 2013

    @darthdeus
    Author

    @JanKanis Yes using and works for small blocks, but it really really really really really doesn't scale.

  8. krader1961 commented on Oct 6, 2016

    @krader1961
    Contributor

    Anyone reading this must also read issue #3414 which explains why using an exception model and looking to Ruby (and possibly Python) for how they trap exceptions is a good idea.

  9. Rush commented on Oct 6, 2016

    @Rush

    Copying my comment from #3414

    Let's add solid error handling to Fish.

    • Ability to detect failed non-zero exit commands and treat them as error in systematic way.
    • Manual checking each command for failure is error-prone and highly redundant
    • Ability to report such errors along with a trace including line of code where the error occured
    • Ability for developers to act on such errors in production environments
    • With a proper handler, ability to report errors to Bugsnag
    • The above gives complicated scripts which modify the environment the ability to rollback all changes should any error occur. Imagine a network bridge setup script which is invoked on remote on a server. This script interacts with network tools, shuts down interfaces, brings them up, checks connectivity. Any of these can fail and ultimately sever the server from outside world. Ability to rescue from arbitrary error gives a tool to bring back the original configs and restore connectivity.

    Possible implementation:
    Given a block of code which is "error rescue enabled" and pushed to the stack, any subsequent stack frame should inherit this property. If an external command is run, or one of a yet to be defined built in commands without prior checking of $status then execution context should jump to a special rescue function or block should be called. It's yet to be defined whether execution can be resumed or not.
    If $status is checked or an ; or is invoked then the error should no longer be rescued from.

    These shouldn't cause error rescue because $status is being checked:

    # assume below code is in error rescue mode
    which nonexistent-command; or echo "Warning: command does not exist"`
    # assume below code is in error rescue mode
    which nonexistent-command
    if test $status != 0
      echo "Warning: command does not exist"`
    end

    Imagine a developer writing something along these lines (and 10x longer):

    ifconfig non-existent-interface up # we want stacktrace here!
    brctl addbr br0
    brctl addif br0 non-existent-interface
    

    Prior art - bash's ugly solution of trap ERR

    Note: there is also set -e which silently kills the script in case of any errors. It effectively prevents

    Way to get better trace http://stackoverflow.com/q/6928946/403571

    #!/bin/bash
    error_report() {
      echo Got error in line ${@}
      exit 1
    }
    
    trap 'error_report $LINENO' ERR
    
    which ddddddddddddd
    echo "Shouldn't get here"

    More info: http://aplawrence.com/Basics/trapping_errors.html

    Syntax proposal with new keyword

    begin
      which ddddddddddd # this fails
      echo "Should not get here"  #running another command without checking `$status`
    rescue
      status --print-stack-trace
      # Could we handle return 1 the same way as in the below proposal?
    end

    Syntax proposal with minor changes to the parser:

    Same changes needed for #1439 (comment)

    function error_handler
      status --print-stack-trace
      return 1 # means not run anything more in the block, return 0 for ignoring error
    end
    
    begin --rescue error_handler
      which ddddddddddd # this fails
      echo "Should not get here"  #running another command without checking `$status` should run our rescue handler
    end

    What do y'all think?

  10. danieljames commented on Oct 6, 2016

    @danieljames
    Contributor

    I don't think #3414 should be considered a duplicate of this issue, it's asking for a lot more, and requires too much code to get the same effect. I don't think it's a good solution for this particular issue.

    I do have a couple of objections to the proposal. I don't think activating errors should be dynamically scoped. A function shouldn't behave differently depending on where it was called from, e.g. if you use this in your script, but call a third party function that doesn't expect to die when an executable fails.

    A problem with begin..rescue is that the behaviour of the code is altered by the end of the block, anything which changes behaviour should be at the beginning so that the reader will see it first. Ruby and python are different because they always raise an exception when there's an error, so there's no change to how the code behaves, just how errors are handled, and it makes sense to do that at the end, because that's how the code flows.

    Btw #763 is also relevant if you want a complete error handling solution. Errors in pipes are a real pain.

  11. presidento commented on Feb 9, 2017

    @presidento

    @Rush I like you idea, especially the "Syntax proposal with minor changes to the parser" part. Additionally, I think it would be good to have some default rescue functions with aliased parameters, like

    begin --fail-on-error
      which ddddddddddd # this fails
      echo "Should not get here"  #running another command without checking `$status` should run our rescue handler
    end
  12. techtonik commented on Jul 24, 2017

    @techtonik

    I am looking for a bash replacement where fail on error is the sane default.

  13. krader1961 commented on Aug 4, 2017

    @krader1961
    Contributor

    I am looking for a bash replacement where fail on error is the sane default.

    FWIW, @techtonik, I used to use set -e in many of my scripts. Then I experienced unexpected, needless, script failures just because an external command returned an unexpected non-zero status. A "failure" status that was typically a warning, not a fatal failure, and should not have stopped the script from running. I soon realized that this mechanism was a crutch that caused more problems than it solved. It is better to explicitly test the exit status of any command whose failure should terminate the script. Too many commands return a non-zero status for non-fatal situations.

    I say this as someone who has been paid to program since 1979 and started using UNIX in the second half of the 1980's (i.e., approximately 30 years ago). I'm not opposed to implementing this feature in fish but it has to be bounded to specific blocks of code (e.g., begin --fail-on-error; ...; end) rather than a global flag.

  14. occivink commented on Aug 4, 2017

    @occivink
    Contributor

    @techtonik you might be interested in elvish.

  15. 18 remaining items

  16. faho commented on Dec 11, 2019

    @faho
    Member

    Is there any updates on this?

    There is not. It's a complicated issue. In bash it's changed a couple of times and hasn't been without its problems and detractors, so we'd like to get this right.

    currently have a script with a ton of if $status != 0's, and would love to be able to simplify it!

    Well, ; or return is often an option.

  17. avegancafe commented on Dec 11, 2019

    @avegancafe

    Well, ; or return is often an option.

    Hah I just realized that 5 min after posting that. Definitely empathize with the difficulty of this, tbh the only one that sounded reasonable from the issues/comments I've read thus far is something like begin --fail-on-error, but looks like there wasn't any traction on that

  18. deleted a comment from bicepjai on Mar 21, 2020
  19. max-sixty commented on May 6, 2020

    @max-sixty
  20. faho commented on May 6, 2020

    @faho
  21. max-sixty commented on May 6, 2020

    @max-sixty
  22. faho commented on May 6, 2020

    @faho
  23. stellarpower commented on Jul 30, 2020

    @stellarpower

    I haven't read all the above as was looking to employ this in a script RN, however, just sometihng that came to mind, I like the idea of more formal error handling (like exceptions) although that would be a large job to implement; the main difference is in languages with exception handling this is an inherent model usually all the way down; with a shell of any sort we need a way to convert from atomic system commands to what would constitute an exception, as obviously dd can't throw something back up to us. Interestingly I believe this is the same error first confronting the C++ standards committee with C library functions where typically a returned int or a call to check the status were the only ways of detecting an error.

    For normal situations a non-zero error code is often an indication of an error, so it made me think of the following syntax which I'm just dropping in case it's useful at all

    expect begin
      true # any command in this block
      ls -la # that returns 0 
      systemctl --user start myservice # will continue as "normal"
      false # but a code that is not 0 will exitt the block
    end
    
    expect 0 sudo apt install hello-world # Providing explicit parameters of the codes we expect; one single command
    
    # and a more complex version: 0 < code <= 100 for commands that return information via the code like GNU parallel
    expect -gt 0 -lte 100 parallel -q "zcat {} | bzip2 >{.}.bz2"
    
    expect begin
      expect 2 zfs help # we can nest expects such that we can generally catch non-zero codes but some commands may provide different codes when we want to something particular
    
      ls -la /tmp | grep "hiya" | sed 's/hello/hi/g' # For pipelines and
      test $number -ge 1000 ; and echo "big" ; or echo "small" # compound statements
    
      # we use the "final" value for the whole expresion, that is, for each "line" we take the highest-level return code (or set of codes)
      # and if it is "zeroey"/"successy" (analogous of truthy - but for the specific codes above) then we treat the "line" as having been successful
      # so for most common usage where we expect 0, in a pipeline, all the return codes need to be zero; for a compound statement, the last needs to be 0; for a begin block, the outer level needs to return 0.
    
    end
  24. eguiraud commented on Jul 9, 2021

    @eguiraud

    One more example usecase: I was writing a long script today where I need to run a bunch of complex git commands and other filesystem operations. I would have loved to have a fish --exit-on-nonzero-status myscript.fish (or any of the proposed solutions above, fwiw) rather than having to insert a manual check for the exit code of each of the many commands I want to run.

  25. deleted a comment from egor-tensin on Apr 2, 2022
  26. deleted a comment from Ancient123 on Apr 8, 2022
  27. deleted a comment from avegancafe on Apr 8, 2022
  28. locked as spam and limited conversation to collaborators on Apr 8, 2022
  29. faho commented on Apr 8, 2022

    @faho
    Member

    Okay this issue is attracting a bunch of unhelpful comments and hasn't had something constructive in a while so I have now locked it.

    We would like something to make error handling easier in fish, but it's not going to be a straight clone of set -euo pipefail.

    If someone has a fleshed out idea for a design, we're all ears, but it's going to have to address the shortcomings of that "bash strict mode".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions