bash

Bash, the Bourne Again Shell, is one of the most ubiquitous shells on nix systems, being either the default or included in distributions.

If you use bash a lot, you will find that make can also be used for lots of things.

Snippets

To run a command in an infinite loop, do something like this: while true; do echo hi mom; sleep 1; done

To run a command a set number of times, do: for i in {1..10}; do echo howdy; sleep 1; done

To redirect stdout and stderr from a command: foo > /dev/null 2> err.txt

To pass along your arguments when creating a wrapper: wrapped-script "$@"

To compare two strings: if [[ "$1" = "$2" ]] ; then ...

To do a basic if-then/else check on a file exist:

if ! test -d /path/to/file ; then
  echo it does not exist;
else
  echo exists;
fi

Script template

This is what a simple bash script template might look like.

It does a variety of things, just remove the sections you don't care for.

#!/bin/bash

set -euo pipefail
# add -x to trace

# help function
function show_help() {
  cat <<- EOF
  USAGE: my-script [--foo foo] [--bar bar] [--flag] args...

  OPTIONS:
    --foo   - do foo
    --bar   - do bar
    --flag  - set flag
EOF
  exit
}

# handle options as flags, key/value or positional arguments
POS_ARGS=()
FLAG_SET=false
while [[ $# -gt 0 ]]; do
  key="$1"
  case $key in
    --flag)
      FLAG_SET=true
      ;;
    --foo)
      shift
      FOO="$1"
      ;;
    --bar)
      shift
      BAR="$1"
      ;;
    --help)
      show_help
      ;;
    *)
      POS_ARGS=[${#POS_ARGS[@]}]="${1} "
      ;;
  esac
  shift
done

# figure out where the script is at to call other files around it
self=$(readlink -f "${BASH_SOURCE[0]}") # follow link
echo full path is $self
echo dir name is $(dirname $self)
echo base name is $(basename $self)
# full path is /Users/someone/scratch/my-script
# dir name is /Users/someone/scratch
# base name is my-script

set -euo means 'exit immediately', 'treat unset variables as errors on parameter expansion', 'option pipefail' (return value of rightmost non-zero result in pipes).

Happy scripting!

Home