Let's translate from Python to Bash chunk-by-chunk.
Python:
#!/usr/bin/env python3
import sys, os
linelist = list(sys.stdin)
Bash:
#!/usr/bin/env bash
linelist=()
while IFS= read -r line; do
linelist+=("$line")
done
Python:
# gets the biggest line
biggest_line_size = 0
for line in linelist:
line_lenght = len(line)
if line_lenght > biggest_line_size:
biggest_line_size = line_lenght
Bash:
biggest_line_size=0
for line in "${linelist[@]}"; do
# caveat alert: the length of a tab character is 1
line_length=${#line}
if ((line_length > biggest_line_size)); then
biggest_line_size=$line_length
fi
done
Python:
columns = int(os.popen('tput cols', 'r').read())
offset = biggest_line_size / 2
perfect_center = columns / 2
padsize = int(perfect_center - offset)
spacing = ' ' * padsize # space char
Bash:
columns=$(tput cols)
# caveat alert: division truncates to integer value in Bash
((offset = biggest_line_size / 2))
((perfect_center = columns / 2))
((padsize = perfect_center - offset))
if ((padsize > 0)); then
spacing=$(printf "%*s" $padsize "")
else
spacing=
fi
Python:
text = str()
for line in linelist:
text += (spacing + line)
divider = spacing + ('─' * int(biggest_line_size)) # unicode 0x2500
text += divider
print(text, end="\n"*2)
Bash:
for line in "${linelist[@]}"; do
echo "$spacing$line"
done
printf $spacing
for ((i = 0; i < biggest_line_size; i++)); do
printf -- -
done
echo
The complete script for easier copy-pasting:
#!/usr/bin/env bash
linelist=()
while IFS= read -r line; do
linelist+=("$line")
done
biggest_line_size=0
for line in "${linelist[@]}"; do
line_length=${#line}
if ((line_length > biggest_line_size)); then
biggest_line_size=$line_length
fi
done
columns=$(tput cols)
((offset = biggest_line_size / 2))
((perfect_center = columns / 2))
((padsize = perfect_center - offset))
spacing=$(printf "%*s" $padsize "")
for line in "${linelist[@]}"; do
echo "$spacing$line"
done
printf "$spacing"
for ((i = 0; i < biggest_line_size; i++)); do
printf ─ # unicode 0x2500
done
echo
Summary of caveats
Division in Bash truncates. So the values of offset, perfect_center and padsize might be slightly different.
There are some issues that exist in the original Python code too:
The length of a tab character is 1. This will cause sometimes the divider line to look shorter than the longest line, like this:
Q: Why did the tachyon cross the road?
A: Because it was on the other side.
──────────────────────────────────────
If some lines are longer than columns, the divider line would be probably better using the length of columns instead of the longest line.