Last active
September 19, 2023 20:07
-
-
Save blakek/5d3764dc61ec11cb130a75f7f19938b1 to your computer and use it in GitHub Desktop.
Stream output limit in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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