Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

executable file 99 lines (87 sloc) 2.067 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
#!/usr/bin/env bash
#
# spark
# https://github.com/holman/spark
#
# Generates sparklines for a set of data.
#
# Here's a a good web-based sparkline generator that was a bit of inspiration
# for spark:
#
# https://datacollective.org/sparkblocks
#
# spark takes a comma-separated list of data and then prints a sparkline out of
# it.
#
# Examples:
#
# spark 1 5 22 13 53
# # => ▁▁▃▂▇
#
# spark 0 30 55 80 33 150
# # => ▁▂▃▅▂▇
#
# spark -h
# # => Prints the spark help text.

# Generates sparklines.
#
# $1 - The data we'd like to graph.
spark()
{
  local n numbers=

  # find min/max values
  local min=0xffffffff max=0

  for n in ${@//,/ }
  do
    # on Linux (or with bash4) we could use `printf %.0f $n` here to
    # round the number but that doesn't work on OS X (bash3) nor does
    # `awk '{printf "%.0f",$1}' <<< $n` work, so just cut it off
    n=${n%.*}
    (( n < min )) && min=$n
    (( n > max )) && max=$n
    numbers=$numbers${numbers:+ }$n
  done


  # print ticks
if [[ $CLICOLOR -eq '1' ]]
then
  green=$(tput setaf 2)
  blue=$(tput setaf 4)
  red=$(tput setaf 1)
  reset=$(tput sgr0)
  local ticks=(${green}${reset} ${green}${reset} ${green}${reset} ${blue}${reset} ${blue}${reset} ${blue}${reset} ${red}${reset} ${red}${reset})
else
  local ticks=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █)
fi

  local f=$(( (($max-$min)<<8)/(${#ticks[@]}-1) ))
(( f < 1 )) && f=1

for n in $numbers
do
echo -n ${ticks[$(( ((($n-$min)<<8)/$f) ))]}
  done
  echo
}

# If we're being sourced, don't worry about such things
if [ "$BASH_SOURCE" == "$0" ]; then
  # Prints the help text for spark.
  help()
  {
    cat <<EOF

USAGE:
spark [-h] VALUE,...

EXAMPLES:
spark 1 5 22 13 53
▁▁▃▂█
spark 0,30,55,80,33,150
▁▂▃▄▂█
echo 9 13 5 17 1 | spark
▄▆▂█▁
EOF
  }

  # show help for no arguments if stdin is a terminal
  if { [ -z "$1" ] && [ -t 0 ] ; } || [ "$1" == '-h' ]
  then
    help
exit 0
  fi

  spark ${@:-`cat`}
fi
Something went wrong with that request. Please try again.