‹ BackHN Continuity

Thread

Telling a Computer to Do Things

91 points · 37 comments · vismit2000

  1. necovek · · focus · HN ↗
    I was pretty close in guessing what they believe was "wrong" (or really, superfluous) with their initial shell script example.

    I'd even drop the "if" from their footnote version, and go with simply

      npm install || (echo "boom" && exit)
    
    (Not exactly equivalent because there won't be an "exit" if echo fails, but it's my preferred instict over ";") Also, "(" starts a subshell, if we are being pedantic.
    1. Sharlin · · focus · HN ↗
      I wonder if there’s some obscure syntax for "do this if the preceding command fails and propagate its exit code". For just returning some error you can of course have something like `die("boom")` (though not as a builtin?) but sometimes it’s useful to know the exact code.
      1. dasyatidprime · · focus · HN ↗
        if table --warble farble; then :; else table_ec=$?; echo "Garble warble farble! :(" >&2; exit $table_ec; fi

        Works in dash/bash/zsh at least; not 100% sure whether the behavior of $? on the command in an if test is mandated by POSIX and/or portable. Note that you can't replace the empty then-branch with a negated condition because the negation also eats the return code.

        Also, absolutely correct propagation is essentially impossible (but usually not useful anyway), because some errors might be unexpected signal exits or inability to find the command in the first place, and those will get punned onto other nonzero exit codes. I forget the exact conventions OTTOMH but generally they're in the high half (≥128).

        1. necovek · · focus · HN ↗
          Signals get a 128+n, with n being the signal code.

          Where texinfo is available, "info bash" is a great reference; "man bash" is everything in a single page — so less manageable — but you can look for BUILTIN section, which documents "exit" built-in function (among other things).

Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.