frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Bash Strict Mode (2014)

http://redsymbol.net/articles/unofficial-bash-strict-mode/
31•dcminter•2d ago

Comments

deathanatos•1h ago
Or just don't use Bash. Python is a great scripting language, and won't blow your foot off if you try to iterate through an array.

Other than that, yeah, if you must use bash, set -eu -o pipefail; the IFS is new and mildly interesting idea to me.

> The idea is that if a reference is made at runtime to an undefined variable, bash has a syntax for declaring a default value, using the ":-" operator:

Just note that defaulting an undefined variable to a value (let's use a default value of "fallback") for these examples is,

  ${foo-fallback}
The syntax,

  ${foo:-fallback}
means "use 'fallback' if foo is unset or is equal to "". (The :, specifically triggers this; there's a bunch of others, like +, which is "use alternate value", or, you'll get the value if the parameter is defined, nothing otherwise.

  if [[ "${foo+set}" == "set" ]]; then
    # foo is not undefined.
  fi
And similarly,

  ${foo:+triggered}
will emit triggered if foo is set and not empty.)

See "Parameter Expansion" in the manual. I hate this syntax, but it is the syntax one must use to check for undefined-ness.

xelxebar•47m ago
Permit me to vent just a bit:

> Python is a great scripting language, and won't blow your foot off if you try to iterate through an array.

I kind of hate that every time the topic of shell scripting comes up, we get a troop of comments touting this mindless nonsense. Python has footguns, too. Heck, it's absolutely terrible and hacky if you try to do concatenative programming with it. Does that mean it should never be used?

Instead of bashing the language, why not learn bash the language? IME, most of the industry has just absorbed shell programming haphazardly through osmosis, and almost always tries to shove the square pegs of OOP and FP into the round hole that is bash. No wonder people are having a bad time.

In contrast, a data-first design that heavily normalizes data into line-oriented tables and passes information around in pipes results in simple, direct code IME. Stop trying to use arrays and embrace data normalization and text. Also, a lot of pain comes from simply not learning the facilities, e.g. the set builtin obviates most uses of string munging and exec:

    set -- "$@" --file 'filename with spaces.pdf'
    set -- "$@" 'data|blob with "dangerous" characters'
    set -- "$@" "$etc"
    some_command "$@"
Anyway, the senseless bash hate is somewhat of a pet peeve of mine. Exunt.
3eb7988a1663•27m ago
All languages have foot guns, but bash is on the more explodey end of the scale. It is not senseless to note that if you can use a safer tool, you should consider it.

C/C++ got us really far, but greenfield projects are moving to safer languages where they can. Expert low level programmers, armed with all of the available linting tools are still making unfortunate mistakes. At some point we should switch to something better.

oguz-ismail•18m ago
> At some point we should switch to something better.

Agree. Python isn't it though

matheusmoreira•1h ago
This honestly should be the default for all scripts. There are so many little annoyances in bash that would make it great if they were changed and improved. Sadly there's just no changing certain things.

My number one wishlist feature was a simple library system. Essentially just let me source files by name by searching in some standard user location. I actually wrote and submitted patches for this but it just didn't work out. Maintained my own version for a while and it was nice but not enough to justify the maintenance burden. Bash's number one feature is being the historical default shell on virtually every Linux distribution, without that there's no point.

At least we've got shellcheck.

dhamidi•46m ago
The `source` builtin searches through all directories on PATH, not quite a library system, but useable with a bit of discipline in the to-be-sourced shellscripts.
abathur•36m ago
When you say library system, do you mean something more or less like a separate search path and tools for managing it?

I've written a little about how we can more or less accomplish something like meaningfully-reusable shell libraries in the nix ecosystem. I think https://www.t-ravis.com/post/shell/the_missing_comprehensive... lays out the general idea but you can also pick through how my bashrc integrates libraries/modules (https://github.com/abathur/bashrc.nix).

(I'm just dropping these in bin, since that works with existing search path for source. Not ideal, but the generally explicit nature of dependencies in nix minimizes how much things can leak where they aren't meant to go.)

oneshtein•19m ago
bash-modules project tries to implement "modules", which works in strict mode, but it got no traction.
heybrendan•1h ago
From 2014 [1].

This seems to be posted once per year (at least); however, hardly a complaint as the discussion tends to be high quality.

My personal mantra is if it's over 10~20 lines, I should arguably be using another language, like Python (and perhaps correspondingly, subprocess [2], if I'm in a hurry).

[1] https://web.archive.org/web/20140523002853/http://redsymbol....

[2] https://docs.python.org/3/library/subprocess.html

esafak•51m ago
It's time to stop using these archaic shells, and make sure the newer ones are packaged for and included with popular operating systems. Better scripting languages have been offered in shells for a long time: https://en.wikipedia.org/wiki/Scsh

These days I've settled on https://www.nushell.sh/

tux1968•40m ago
I think https://oils.pub/ has a good shot at being the eventual replacement because it has a very strong transition story. Being backward compatible, while allowing you to progressively embrace a modern replacement, is pretty powerful.
chubot•1h ago
I use essentially this, but I think this post is over 10 years old (needs a date), and it's now INCOMPLETE.

bash introduced an option to respect rather than ignore errors within command sub processes years ago. So if you want to be safer, do something like:

    #!/bin/bash
    set -euo pipefail
    shopt -s inherit_errexit 
That works as-is in OSH, which is part of https://oils.pub/

(edit: the last time this came up was a year ago, and here's a more concrete example - https://lobste.rs/s/1wohaz/posix_2024_changes#c_9oo1av )

---

But that's STILL incomplete because POSIX mandates that errors be LOST. That is, it mandates broken error handling.

For example, there what I call the "if myfunc" pitfall

    set -e

    my-deploy-func  # errors respected

    if ! my-deploy-func; then   # errors lost
      echo failed
    fi
    my-deploy-func || echo fail  # errors lost
But even if you fix that, it's still not enough.

---

I describe all the problems in this doc, e.g. waiting for process subs:

YSH Fixes Shell's Error Handling (errexit) - https://oils.pub/release/latest/doc/error-handling.html

Summary: YSH fixes all shell error handling issues. This was surprisingly hard and required many iterations, but it has stood up to scrutiny.

For contrast, here is a recent attempt at fixing bash, which is also incomplete, and I argue is a horrible language design: https://lobste.rs/s/kidktn/bash_patch_add_shopt_for_implicit...

aidenn0•1h ago
What are your thoughts on pipefail in bash? I know ysh (and maybe osh too?) are smart about a -13 result from a pipe, but I stopped using pipefail since the return value can be based on a race, causing things to randomly not work at some point in the future.

[edit]

Per the link you posted osh treats a -13 result as success with sigpipe_status_ok, but I'm still interested in your thoughts on if pipefail is better or worse to recommend as "always on" for bash.

xelxebar•41m ago
I kind of feel like set -o errexit (i.e. set -e) provides enough unexpected semantics that explicit error handling makes more sense. One thing that often trips people up is this:

    set -e
    [ -f nonexistent ] && do_something
    echo 'this line runs'
but

    set -e
    f(){ [ -f nonexistent ] && do_something; }
    f
    echo 'This line does not run'
modulo some version differences.
kayson•55m ago
Or use shellcheck: https://www.shellcheck.net/
burnt-resistor•23m ago
Tl;dr: Use both because they aren't mutex.

Shellcheck isn't a complete solution, and running -e mode is essential to smaller bash files. Shellcheck even knows if a script is in -e mode or not.

cendyne•50m ago
If you ever try something like this with another bash-hackery tool like NVM, you will have a very bad time.
jacob2161•45m ago
Stylistically, I much prefer

  #!/bin/bash
  set -o errexit
  set -o nounset
  set -o pipefail
It reminds me when I wrote a lot of Perl:

  #!/usr/bin/perl
  use strict;
  use warnings;
I also prefer --long --args everywhere possible and a comment on any short flag unless it's incredibly common.

I've been writing all my Bash scripts like this for ~15 years and it's definitely the way to go.

Waterluvian•36m ago
Yeah! I feel like long args very strongly fits with the overall idea of this blog post: when you are running a script you care about different things and want different behaviours than when you’re working interactively.

The short args are great for when you’re typing into a terminal. But when you’re writing and saving a script, be descriptive! One of the most irritating things about bash (and Linux, I guess?) is how magical all the -FEU -lh 3 -B 1 incantations are. They give off a vibe I call “nerd snobbish” where it’s a sort of “oh you don’t know what that all means? How fretful!”

burnt-resistor•25m ago
Too damn verbose and you're assuming bash is at /bin. This will cause problems in nix and other environments where bash should be found on the path instead.

Always, always unless the script is guaranteed to not be portable to other platforms:

    #!/usr/bin/env bash
    ...
vivzkestrel•36m ago
Lots of arguments against not using set -euo pipefail https://www.reddit.com/r/commandline/comments/g1vsxk/comment... anything you wanna say about this?
awestroke•16m ago
euo pipefail has been the one good thing with bash. I'll start looking at alternatives now
vivzkestrel•33m ago
Again another great read about why you should NOT use this https://mywiki.wooledge.org/BashFAQ/105
burnt-resistor•26m ago

   set -Eeuo pipefail

It's missing -E to respect traps.
tomhow•26m ago
Use the unofficial Bash strict mode - https://news.ycombinator.com/item?id=8054440 - July 2014 (36 comments)

Why is choral music harder to appreciate?

https://marginalrevolution.com/marginalrevolution/2025/08/why-is-choral-music-harder-to-appreciat...
8•surprisetalk•2d ago•1 comments

Show HN: Sping – An HTTP/TCP latency tool that's easy on the eye

https://dseltzer.gitlab.io/sping/docs/
79•zorlack•5h ago•5 comments

Busy beaver hunters reach numbers that overwhelm ordinary math

https://www.quantamagazine.org/busy-beaver-hunters-reach-numbers-that-overwhelm-ordinary-math-202...
69•defrost•2d ago•13 comments

From Hackathon to YC

https://www.producthunt.com/p/april-yc-s25/from-hackathon-to-yc
12•rmason•6h ago•9 comments

The two versions of Parquet

https://www.jeronimo.dev/the-two-versions-of-parquet/
146•tanelpoder•3d ago•33 comments

We put a coding agent in a while loop

https://github.com/repomirrorhq/repomirror/blob/main/repomirror.md
164•sfarshid•12h ago•112 comments

Is 4chan the perfect Pirate Bay poster child to justify wider UK site-blocking?

https://torrentfreak.com/uk-govt-finds-ideal-pirate-bay-poster-boy-to-sell-blocking-of-non-pirate...
194•gloxkiqcza•12h ago•167 comments

German contest to live in depopulated Soviet-era city proves global hit

https://www.theguardian.com/world/2025/aug/21/german-contest-to-live-in-depopulated-soviet-era-ci...
36•c420•3d ago•30 comments

Y Combinator files brief supporting Epic Games, says store fees stifle startups

https://www.macrumors.com/2025/08/21/y-combinator-epic-games-amicus-brief/
124•greenburger•3d ago•111 comments

The Unix-Haters Handbook (1994) [pdf]

https://simson.net/ref/ugh.pdf
14•oliverkwebb•4h ago•2 comments

Ghrc.io appears to be malicious

https://bmitch.net/blog/2025-08-22-ghrc-appears-malicious/
277•todsacerdoti•5h ago•36 comments

Trees on city streets cope with drought by drinking from leaky pipes

https://www.newscientist.com/article/2487804-trees-on-city-streets-cope-with-drought-by-drinking-...
159•bookofjoe•2d ago•84 comments

Show HN: Decentralized Bitcoin Incentives via QR Codes

https://github.com/DT7QR/Bitcoin-Rewards-System-Proposal
6•Yodan2025•3h ago•0 comments

Making games in Go: 3 months without LLMs vs. 3 days with LLMs

https://marianogappa.github.io/software/2025/08/24/i-made-two-card-games-in-go/
269•maloga•14h ago•189 comments

Burner Phone 101

https://rebeccawilliams.info/burner-phone-101/
305•CharlesW•4d ago•122 comments

A Brilliant and Nearby One-off Fast Radio Burst Localized to 13 pc Precision

https://iopscience.iop.org/article/10.3847/2041-8213/adf62f
54•gnabgib•9h ago•7 comments

Everything I know about good API design

https://www.seangoedecke.com/good-api-design/
227•ahamez•9h ago•84 comments

Bash Strict Mode (2014)

http://redsymbol.net/articles/unofficial-bash-strict-mode/
31•dcminter•2d ago•25 comments

Cloudflare incident on August 21, 2025

https://blog.cloudflare.com/cloudflare-incident-on-august-21-2025/
153•achalshah•3d ago•32 comments

How many paths of length K are there between A and B? (2021)

https://horace.io/walks
21•jxmorris12•8h ago•4 comments

Show HN: Clearcam – Add AI object detection to your IP CCTV cameras

https://github.com/roryclear/clearcam
169•roryclear•17h ago•47 comments

Uncle Sam shouldn't own Intel stock

https://www.wsj.com/opinion/uncle-sam-shouldnt-own-intel-stock-ccd6986d
99•aspenmayer•7h ago•112 comments

Halt and Catch Fire Syllabus (2021)

https://bits.ashleyblewer.com/halt-and-catch-fire-syllabus/
118•Kye•8h ago•34 comments

My ZIP isn't your ZIP: Identifying and exploiting semantic gaps between parsers

https://www.usenix.org/conference/usenixsecurity25/presentation/you
47•layer8•3d ago•19 comments

Claim: GPT-5-pro can prove new interesting mathematics

https://twitter.com/SebastienBubeck/status/1958198661139009862
126•marcuschong•4d ago•86 comments

Comet AI browser can get prompt injected from any site, drain your bank account

https://twitter.com/zack_overflow/status/1959308058200551721
504•helloplanets•13h ago•177 comments

How to check if your Apple Silicon Mac is booting securely

https://eclecticlight.co/2025/08/21/how-to-check-if-your-apple-silicon-mac-is-booting-securely/
60•shorden•5h ago•13 comments

Show HN: I Built a XSLT Blog Framework

https://vgr.land/content/posts/20250821.xml
39•vgr-land•11h ago•16 comments

NASA's Juno mission leaves legacy of science at Jupiter

https://www.scientificamerican.com/article/how-nasas-juno-probe-changed-everything-we-know-about-...
67•apress•3d ago•29 comments

Iterative DFS with stack-based graph traversal (2024)

https://dwf.dev/blog/2024/09/23/2024/dfs-iterative-stack-based
29•cpp_frog•3d ago•3 comments