NASutils Knowledge BaseUnofficialPolski

Bash · lesson 29 of 30 · Tools for the NAS · bonusBuild a notepad

mapfile loads the notes into an array, case chooses add, list or delete.

Programming on the NAS › Bash in 30 lessons

29-notepad.sh Download 29-notepad.sh

#!/usr/app/TurboShell/bin/bash
# A notepad: add TEXT, list, delete NUMBER. The notes are in notes.txt.
set -euo pipefail
file=notes.txt
touch "$file"
mapfile -t notes <"$file"

save() {
  if ((${#notes[@]})); then
    printf '%s\n' "${notes[@]}" >"$file"
  else
    : >"$file"
  fi
}

case ${1:-} in
  add)
    text=${2:-}
    if [[ -z $text ]]; then
      echo "Nothing added: give a text"
      exit 1
    fi
    notes+=("${text//$'\n'/ }")
    save
    echo "Added note ${#notes[@]}"
    ;;
  list)
    ((${#notes[@]})) || echo "No notes"
    for i in "${!notes[@]}"; do
      echo "$((i + 1)). ${notes[i]}"
    done
    ;;
  delete)
    number=${2:-0}
    if [[ ! $number =~ ^[1-9][0-9]{0,5}$ ]] || ((number > ${#notes[@]})); then
      echo "There is no such note"
      exit 1
    fi
    unset 'notes[number - 1]'
    save
    echo "Deleted note $number"
    ;;
  *)
    echo "usage: add TEXT | list | delete NUMBER"
    exit 2
    ;;
esac

Terminal

$ bash 29-notepad.sh add "Buy two disks"
Added note 1
$ bash 29-notepad.sh add "Check the backup"
Added note 2
$ bash 29-notepad.sh list
1. Buy two disks
2. Check the backup
$ bash 29-notepad.sh delete 1
Deleted note 1
$ bash 29-notepad.sh delete 9; echo "exit code $?"
There is no such note
exit code 1
$ bash 29-notepad.sh list
1. Check the backup

Exercise

Add a command find TEXT that shows matching notes.

How it works

  • touch makes notes.txt if it is missing, and mapfile reads its lines into the array notes.
  • case runs add, list or delete.
  • The pattern ^[1-9][0-9]{0,5}$ lets through only whole numbers from 1 to 999999, before Bash counts with them; a number larger than the count of notes stops the program too.
  • unset takes one note out and the function save writes the rest.