taladar,

Good point, forgot one of the basics.

Also, to make your scripts more readable and less error prone use something like


<span style="color:#323232;">if [[ $# -gt 0 ]] && [[ "$1" == "--dry-run" ]]; then
</span><span style="color:#323232;">  dry_run=1
</span><span style="color:#323232;">  shift
</span><span style="color:#323232;">else
</span><span style="color:#323232;">  dry_run=0
</span><span style="color:#323232;">fi
</span><span style="color:#323232;">
</span><span style="color:#323232;">if [[ $# != 3 ]]; then
</span><span style="color:#323232;">  echo "Usage: $0 [ --dry-run ] <description of foo> <description of bar> <description of baz>" >&2
</span><span style="color:#323232;">  exit 1
</span><span style="color:#323232;">fi
</span><span style="color:#323232;">
</span><span style="color:#323232;">foo="$1"
</span><span style="color:#323232;">shift
</span><span style="color:#323232;">bar="$1"
</span><span style="color:#323232;">shift
</span><span style="color:#323232;">baz="$1"
</span><span style="color:#323232;">shift
</span>

at the start of your script to name your parameters and provide usage information if the parameters did not match what you expected. The shift and use of $1 at the bottom allows for easy addition and removal of parameters anywhere without renumbering the variables.

Obviously this is only for the 90% of scripts that do not have overly complex parameter needs. For those you probably want to use something like getopt or another language with libraries like the excellent clap crate in Rust.

  • All
  • Subscribed
  • Moderated
  • Favorites
  • linux@lemmy.ml
  • fightinggames
  • All magazines