Skip to content

Instantly share code, notes, and snippets.

@blakek
Last active September 19, 2023 20:07
Show Gist options
  • Save blakek/5d3764dc61ec11cb130a75f7f19938b1 to your computer and use it in GitHub Desktop.
Save blakek/5d3764dc61ec11cb130a75f7f19938b1 to your computer and use it in GitHub Desktop.
Stream output limit in Bash
#! /usr/bin/env bash
# Formatting helpers
bold() {
printf "\033[1m%s\033[0m\n" "$*"
}
dim() {
printf "\033[2m%s\033[0m\n" "$*"
}
stream_output() {
local max_lines="${1:-10}"
local buffer=()
while read -r line; do
buffer+=("$(dim "$line")")
buffer_length="${#buffer[@]}"
if ((buffer_length > max_lines)); then
buffer=("${buffer[@]:1}")
fi
if ((buffer_length > 1)); then
for ((i = 0; i < buffer_length - 1; i++)); do
tput cuu 1
tput el
done
fi
printf "%s\n" "${buffer[@]}"
done
}
for i in {1..20}; do
echo "line $i"
sleep 0.1
done | stream_output 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment