top | item 45010142

(no title)

jacob2161 | 6 months 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.

discuss

order

Waterluvian|6 months 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!”

Intralexical|6 months ago

Long args are less portable, unfortunately. IIRC they're not POSIX at all, and also likelier to be different across GNU, BusyBox, BSD, and Mac tools.

burnt-resistor|6 months 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
    ...

jacob2161|6 months ago

You're assuming env is in /usr/bin?

There are real environments where it's at /bin/env.

Running a script with

  bash script.sh
Works on any system with bash in the path, doesn't require that it be executable, and is usually the ideal way to execute them.

I don't really believe in trying to write portable Bash scripts. There's a lot more to it than just getting the shebang right. Systems and commands tend to have subtle differences and flags are often incompatible. Lots of branching logic makes them hideous quickly.

I prefer to write a script for each platform or just write a small portable Go program and compile it for each platform.

I'm almost always writing Bash scripts for Linux that run in Debian-based containers, where using /bin/bash is entirely correct and safe.

Regarding verbosity, most people come to appreciate a little verbosity in exchange for clarity with more experience. Clever and compact code is almost never what you want in production code.