Skip to content

Bash Style

Bash script style standards: 2-space indentation, 80-character lines, and clean multiline strings.

Pattern

Follow all rules in Code Style

All bash scripts must follow language-agnostic style standards: 2-space indentation, 80-character line limit.

Use strip_indent for clean multiline strings

Multiline strings with indentation become part of the string content. The strip_indent function preserves code readability while producing correctly formatted output.

DON'T let indentation become part of string content

bash
echo "
    This text will have 4 spaces before it
    Every line includes the indentation
  "

DO use strip_indent to remove common indentation

bash
echo "
    This text will be left-aligned
    Common indentation is removed
  " | strip_indent

The strip_indent Function:

bash
strip_indent() {
  local text min_indent
  text=$(cat)
  text="${text//$'\r'/}"
  min_indent=$(printf "%s\n" "$text" \
    | grep -v '^[[:space:]]*$' \
    | sed 's/[^[:space:]].*//' \
    | awk '{ print length }' \
    | sort -n \
    | head -n1)
  if [[ -n "$min_indent" && "$min_indent" -gt 0 ]]; then
    printf "%s\n" "$text" \
      | sed "s/^[[:space:]]\{0,$min_indent\}//"
  else
    printf "%s\n" "$text"
  fi
}

Use one_line to collapse multiline strings

When a long string must fit on one line (e.g., error messages, log output), use one_line to collapse newlines and adjacent whitespace into single spaces.

DON'T write unreadable single-line strings

bash
fail "Supervisor did not detect crash (expected 'Crash detected, triggering restart')"

DO use one_line for readable long strings

bash
fail "$(echo "
    Supervisor did not detect crash
    (expected 'Crash detected, triggering restart')
  " | one_line)"

The one_line function:

Collapses a multiline string into a single line. Replaces newlines with spaces and normalizes adjacent whitespace to single spaces. Trims leading and trailing whitespace from the result.

bash
one_line() {
  tr '\n' ' ' \
    | sed 's/[[:space:]]\{2,\}/ /g; s/^[[:space:]]*//; s/[[:space:]]*$//'
}