Skip to content

Instantly share code, notes, and snippets.

@fabiolimace
Last active February 2, 2025 16:22
Show Gist options
  • Save fabiolimace/9837005aabe2af959b604aa23b465d7e to your computer and use it in GitHub Desktop.
Save fabiolimace/9837005aabe2af959b604aa23b465d7e to your computer and use it in GitHub Desktop.
Shows a text file page by page in intervals of N seconds.
#!/usr/bin/bash
#
# Shows a text file page by page in intervals of N seconds.
#
# If no page is given, it starts in the last page from history.
#
# Usage:
#
# ./reader.sh FILE [PAGE] [SECONDS]
#
# Parameters:
#
# FILE: a plain text file.
# PAGE: the number of page to start.
# SECONDS: the automatic page change interval in seconds. The default is 180 (3 minutes).
#
# Commands:
#
# p: pause
# u: page up
# d: page down
# q: page down
# SPACE: next page
# ENTER: next page
# ESCAPE: exit
#
# The commands page up and page down dont log the progress.
#
[ -f "$1" ] || exit 1;
[ "${2-1}" -ge 1 ] || exit 1;
file="${1}";
page="${2-0}";
secs="${3-180}";
temp=`mktemp`;
if [ ${page} -gt 0 ]; then
p=${page};
else
# get the last progress
touch $HOME/.reader.log
p=`awk 'END { p = $3 ? $3 : 1; print p }' $HOME/.reader.log`;
fi;
s=0;
t=0;
n=30; # fixed number of lines per page
w=80; # fixed number of characters per page
pageup() {
[ ${p} -gt 1 ] && p=`expr ${p} \- 1`;
}
pagedn() {
[ ${p} -le `expr ${max} \/ ${n}` ] && p=`expr ${p} \+ 1`;
}
turnpg() {
history;
pagedn;
}
cleanup() {
rm -f "${temp}";
}
goodbye() {
echo "";
echo "Good bye!";
echo "";
history;
cleanup;
exit 0;
}
history() {
t=$(expr $(date +"%s") \- ${t})
# log if more than 10s
[ $t -le 10 ] && return;
# History fields: file name, last page number, duration in seconds (>10s)
echo -e "`date +"%F_%T"`\t`realpath ${file}`\t${p}\t${t}" >> $HOME/.reader.log
}
control() {
t=$(date +"%s");
local i=0;
for i in `seq ${secs} -1 1`; do
# show remaining time
if [ ${i} -le 30 ]; then
local j=`expr ${i} \- 1`;
local time="`date -u -d @${j} +"%T"`";
printf "\r${time}";
fi;
read -s -N 1 -t 1 key;
# pause the reading progress
if [ "$key" = 'p' ] || [ "$key" = 'P' ]; then
local blinking="\r\033[33;5m%s\033[0m";
printf "${blinking}" "(PAUSED)";
read -s -N 1;
continue;
fi;
[ -n "$key" ] && break;
done;
[ -z "$key" ] && turnpg;
case $key in
[uU] ) pageup;;
[dD] ) pagedn;;
[qQ] ) goodbye;;
$'\x20' ) turnpg;; # SPACE
$'\x0a' ) turnpg;; # ENTER
$'\e' ) goodbye;; # ESCAPEl
esac
}
main() {
trap goodbye SIGINT
fold -s -w $w "${file}" > "${temp}";
max=`wc -l ${temp} | awk '{print $1}'`;
while true; do
s=`expr \( ${p} \- 1 \) \* ${n} \+ 1`;
if [[ ${s} -gt ${max} ]]; then exit 0; fi;
clear;
echo;
echo "- - - - - - - - - - - - - - - - - -";
echo;
sed -n "${s},+${n}p" "${temp}";
echo;
echo "- - - - - - - - - - - - - - - - - -";
echo;
echo "[${p}]";
echo;
control;
done;
}
main;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment