Colorize pattern on CLI

Colorize a pattern in the given input using a neat regex and colorization hack in grep ($ matching all lines but not being able to be highlighted).

color () {
  # Color highlight the pattern in the incoming stream, writing to stdout
  # This effectively matches our PATTERN andy any "$" (line end)
  # But only our PATTERN can be highlighted, line end characters aren't actually there to be highlighted
  local PATTERN=$1

  if [ -z "$1" ]; then
    echo "Usage: color <pattern>"
    echo "Description: Greps input with --color=always -E 'PATTERN|\$' "
    echo "Example: echo \"hello world\" | color \"world\""
    return 1

  fi
  grep --color=always "$PATTERN\|\$"
}

Cleanup After Script Exit

Many of my scripts work with temporary files, usually relative to the scripts directory1, while at the same time using set -e to exit as soon as something fails.

In this scenario the script leaves behind these temporary files by default, which is not desireable.

We can however do a proper cleanup using the trap concept.

[Read More]

Navigate to Script Directory

Often times when writing scripts I want to reference files in the same directory, but keep the script portable in case it is part of a git repository being checked out somewhere else or just the folder getting moved.

[Read More]

Looping Dates macOS

date on MacOS does not support --date, so a workaround is needed. Converting Date to unix epoch, adding one day in epoch and converting back. The Scripty Way Taken from a blog post #!/bin/zsh start=$year-01-01 end=$year-12-31 currentDateTs=$(date -j -f "%Y-%m-%d" $start "+%s") endDateTs=$(date -j -f "%Y-%m-%d" $end "+%s") offset=86400 while [ "$currentDateTs" -le "$endDateTs" ] do date=$(date -j -f "%s" $currentDateTs "+%Y-%m-%d") echo $date currentDateTs=$(($currentDateTs+$offset)) done The Brew Way As I found out long after writing the above you can simply brew install coreutils and get a date command with the --date option. [Read More]
macos  bash