5 ms·
“Exit Traps” Can Make Your Bash Scripts Way More Robust and Reliable
- chasil 3y agoThis appears to be a duplicate of a recent post. https://news.ycombinator.com/item?id=36400465 https://news.ycombinator.com/item?id=36400465
- noahjk 3y agoVery similar to Python's "finally" keyword [0] used in a try block, the "Exit Traps" are meant to allow for clean-up action(s) if a script fails. [0]: https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions https://docs.python.org/3/tutorial/errors.html#defining-clea...
- themoonisachees 3y agoHow is finally() ever useful in any language? What is the difference between try{ #code that can throw errors } catch { #handle error } finally { #code } And try{ #throw err }catch { #handle } #code... Surely in pretty much all languages the two are equivalent, so what is finally's purpose as a token? The trick in this post is different because for one bash doesn't have finally, and even if it did you couldn't use it to catch all of a script's errors.
- anuragsoni 3y ago`finally` will also cover scenarios where the an exception is raised from within catch, or if the catch block doesn't handle an exception that's raised in the `try` block.
- maskros 3y agoIf "handle error" in the catch involves rethrowing the error, or another error, or returning an error code from the function, the "finally" block is _still_ executed. Here's a "fun" example in Javascript: function foo() { try { return 42 } finally { return "boo!" } }
- Rucadi 3y agoIt is better to avoid bash scripts altogether :)
- chasil 3y agoA POSIX shell occupies a special role in scripting. It embodies great power in a small space. $ ll /bin/dash /bin/bash -rwxr-xr-x. 1 root root 1388920 Jan 23 12:16 /bin/bash -rwxr-xr-x. 1 root root 128608 May 9 22:26 /bin/dash $ cat /etc/redhat-release Red Hat Enterprise Linux release 9.2 (Plow) Dash is the Debian/Ubuntu system shell, which supplanted bash sometime ago. You will not find comparable speed and power in that economy of size anywhere else.