Email or username:

Password:

Forgot your password?
Scott Francis

#!/bin/sh

set -euo pipefail

thanks, @b0rk - I've been writing shell for 25+ years and wish I'd been doing this 25+ years ago.

10 comments
Wyatt (🏳️‍⚧️♀?)

@gremlins @darkuncle @b0rk orrr, if you are using an actual posix shell…

(expression) || (echo 'error: thingy happened wrong'; break)

will solve most of these 'issues'.
except unset variables. You should always set any variables you plan to use or check for their existance at the start of a script anyway, especially if you ever used csh you know why.

Bracken :verified:

@darkuncle @b0rk habitually setting pipefail will drive you crazy next time you use grep -q.

Mason Loring Bliss
@darkuncle @b0rk Hrm. So, 1) checking $? is shell-agnostic and generally more appropriate, 2) never rm recursively if you can help it, and check your variables prior to throwing them into something potentially destructive, and 3) how did that grep succeed? In general, shell programming isn't any different from anything else - beware of assumptions.
Nikita

@darkuncle @b0rk beware: `-o pipefail` is not defined in POSIX spec, so `/bin/sh` may not recognize it (`/bin/bash` would)

See ShellCheck Wiki for a POSIXly correct way of achieving a similar effect: shellcheck.net/wiki/SC3040

DELETED

@darkuncle @b0rk 25 years!?!?!

Yikes! Sounds painful!

propapanda :verified:

@darkuncle

One I find really helpful (but missing here) is 'set -x', that prints every line during execution.

@b0rk

Wolf480pl

@darkuncle @b0rk
except `set -e` has bizzare edge cases that can make your script behave in an unexpected way
mywiki.wooledge.org/BashFAQ/10

Go Up