I'm looking for a way to take a text file and put each line one-at-a-time centered on screen with a certain character width.
Sort of like a bare-bones slide show, e.g. seeing the first line until the user presses a key, and then seeing the next line, until all the lines have been viewed.
I suspect there is a basic way to do this in bash, but I haven't found an answer yet.
Best Answer
Something like that:
Name it
centered.sh
and use like that:It will print each line from the given file. Press any key to show the next line. Notice that it's not well tested yet so use with caution and that it'll always print lines starting from the center of the screen so it will make long lines appear more at the bottom.
The first line:
is a shebang. Additionally, I use
env
for its features. I tried to avoid Bash and write this script in POSIX shell but I gave up because especiallyread
was very problematic. You should keep in mind that even though it may seem that Bash is ubiquitous it isn't preset everywhere by default, for example on BSD or small embedded systems with Busybox.In this part:
we check if user provided exactly one parameter and if they didn't we print usage info to standard error and return 1, that means an error to a parent process.
Here
we assign filename parameter that user has passed to a variable
file
that we'll use later.This is a function that actually prints centered text:
There are no function prototypes in Bash so you can't know how many parameters function takes in advance - that one takes only one parameter which is a line to print and it's dereferenced using
$1
This functions first clears the screen, then moves down by lines/2 from the top of the screen to reach center of the screen and then it prints centered line using the method I borrowed from here.That is the loop that reads input file passed by the user and calls
display_center()
function:read
is used with-n 1
to read only one character,-s
to not echo input coming from a terminal and-r
to prevent mangling backslashes. You can learn more aboutread
inhelp read
. We also read from /dev/tty directly because stdin already points to the file - if we didn't tellread
to read from /dev/tty the script would very quickly print all lines from the file and exit immediately without waiting for the user to press a key.