Comment

Comment by chriswarbo

I agree with basically all of this. A few more:

The order of commandline args shouldn't matter.

Env vars are better at passing key/value inputs than commandline arguments are.

Process-substitution can often be used to avoid intermediate files, e.g. `diff some-file <(some command)` rather than `some command > temp; diff some-file temp`

If you're making intermediate files, make a temp dir and `cd` into that

- Delete temp dirs using an exit trap (more reliable than e.g. putting it at the end of the script)

- It may be useful to copy `$PWD` into a variable before changing directory

Be aware of subshells and scope. For example, if we pipe into a loop, the loop is running in a sub-shell, and hence its state will be discarded afterwards:

  LINE_COUNT=0
  some command | while read -r X
  do
    # This runs in a sub-shell; it inherits the initial LINE_COUNT from the parent,
    # but any mutations are limited to the sub-shell, will be discarded
    (( LINE_COUNT++ ))
  done
  echo "$LINE_COUNT"  # This will echo '0', since the incremented version was discarded
Process-substitution can help with this, e.g.

  LINE_COUNT=0
  while read -r X
  do
    # This runs in the main shell; its increments will remain afterwards
    (( LINE_COUNT++ ))
  done < <(some command)
  echo "$LINE_COUNT"  # This will echo the number of lines outputted by 'some command'
parent chriswarbo 4 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton