News for hackers. Stuff that matters.
Re:Techniques I Use to Create a Great User Experience for Sh... by 0xbadcafebee on Saturday September 14, 2024 @12:30PM (#41540825)
If you want a great script user experience, I highly recommend avoiding the use of pipefail. It causes your script to die unexpectedly with no output. You can add traps and error handlers and try to dig out of PIPESTATUS the offending failed intermediate pipe just to tell the user why the program is exiting unexpectedly, but you can't resume code execution from where the exception happened. You're also now writing a complicated ass program that should probably be in a more complete language.

Instead, just check $? and whether a pipe's output has returned anything at all ([ -z "$FOO" ]) or if it looks similar to what you expect. This is good enough for 99% of scripts and allows you to fail gracefully or even just keep going despite the error (which is good enough for 99.99% of cases). You can also still check intermediate pipe return status from PIPESTATUS and handle those errors gracefully too.

Re:Techniques I Use to Create a Great User Experience for Sh... by electromech on Saturday September 14, 2024 @01:48PM (#41541467)
> "It causes your script to die unexpectedly with no output."

Oh? I don't observe this behavior in my testing. Could you share an example? AFAIK, if you don't capture stderr, that should be passed to the user.

> "Instead, just check $? and..."

I agree that careful error handling is ideal. However, IMO it's good defensive practice to start scripts with "-e" and pipefail.

For many/most scripts, it's preferable to fail with inadequate output than to "succeed" but not perform the actions expected by the caller.

Re:Techniques I Use to Create a Great User Experience for Sh... by 0xbadcafebee on Sunday September 15, 2024 @12:14AM (#41545161)
[delayed]
Re:Techniques I Use to Create a Great User Experience for Sh... by ndsipa_pomu on Sunday September 15, 2024 @08:23AM (#41547079)
> the script exited with an error. But it didn't tell you that.

Yes it did, by having a non-zero exit code. However, it didn't explicitly mention that it didn't complete successfully, but that's down to the script writer. I like to include a function to tidy up temporary files etc. when the script exits (e.g. trap __cleanup_before_exit EXIT) and it's easy to also assign a function to run when ERR is triggered - if you wish, you can set it to always provide an error backtrace.