Skip to content

Instantly share code, notes, and snippets.

@stekern
Last active October 6, 2023 13:09
Show Gist options
  • Save stekern/956262bc43ba192aa4d39a6011ca21c1 to your computer and use it in GitHub Desktop.
Save stekern/956262bc43ba192aa4d39a6011ca21c1 to your computer and use it in GitHub Desktop.
shell stuff

shell stuff

A dumping ground for shell commands and regular expressions that should be POSIX-compliant and portable, as well as some bash stuff that should be portable across bash versions (>= 2).

bash

Storing output from command as array

read -r -d '' -a arr < <( command && printf '\0' )

Loop through output from find

while read -r -d ''; do
  echo "$REPLY"
done < <(find "." \( \
  -wholename "*.mp3" \
  -o -wholename "*.wav" \
  \) -print0)

Utility function for asking for confirmation

confirm() {
  local query yn
  query="$1"
  while true; do
    read -rp "$query " yn
    case $yn in
      yes ) return 0;;
      [nN]* ) return 1;;
      * ) printf "Please answer yes or no.\n";;
    esac
  done
}
if confirm "Do you want to do it?"; then
  echo "Doing it!"
fi

Parsing arguments

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'

parse_args() {
  MY_ARG=""
  MY_FLAG=0
  while [ "$#" -gt 0 ]; do
    case "$1" in
      --my-arg)        MY_ARG="$2"; shift; shift; ;;
      --my-flag)       MY_FLAG=1; shift; ;;
      *) echo "Unknown option '$1'"; exit 1 ;;
    esac
  done
  readonly MY_ARG MY_FLAG
  export MY_ARG MY_FLAG
}

main() {
  parse_args "$@"
  echo "$MY_FLAG"
  echo "$MY_ARG"
}

main "$@"

awk

Extract lines between pattern

Can be used to extract the front matter of a markdown file.

awk 'f { if (/---/){
  printf "%s", buf; exit
} else buf = buf $0 ORS }
NR==1 && /---/ { f = 1 }'

sed

Delete from first line until pattern

sed '1,/^---$/d'

POSIX basic regular expressions

Filename with date and text

Match a filename containing date and text (e.g., 2000-01-01-hello-world).

^\([[:digit:]]\{4\}-[[:digit:]]\{2\}-[[:digit:]]\{2\}\)-\([a-zA-Z0-9-]\{1,\}\)$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment