How to center script output in the middle of the screen?

Here I have a binary clock that displays a binary clock in 16 different colors, and I'm trying to make it appear in the center of the screen, but I canโ€™t do it. If you have any suggestions on how to do this, please let me know. thank

color=("0;30" "0;31" "0;32" "0;33" "0;34" "0;35" "0;36" "0;37" "1;30" "1;31" "1;32" "1;33" "1;34" "1;35" "1;36" "1;37")
color2=${#color[*]}
while true;
do
clear
echo -ne '\e['${color[$((RANDOM%color2))]}m
hour=$(date +%H)
minute=$(date +%M)
second=$(date +%S)
hour_binary=$(echo "ibase=10;obase=2;$hour" | bc)
minute_binary=$(echo "ibase=10;obase=2;$minute" | bc)
second_binary=$(echo "ibase=10;obase=2;$second" | bc)
printf "%06d\n" "$hour_binary"
printf "%06d\n" "$minute_binary"
printf "%06d" "$second_binary"
sleep 1
done
+4
source share
2 answers

If you access the center of the terminal window, get the columns and rows of the terminal window with:

COLS=$(tput cols)
ROWS=$(tput lines)
CLOCKWIDTH=8 #I'm assuming a HH:MM:SS format
CENTERCOL=$((COLS/2))
CENTERCOL=$((CENTERCOL-CLOCKWIDTH))
CENTERROW=((ROWS/2))

And then use the tput command to set the cursor position with:

tput cup $CENTERCOL $CENTERROW

. http://www.cyberciti.biz/tips/spice-up-your-unix-linux-shell-scripts.html tput https://www.gnu.org/software/termutils/manual/termutils-2.0/html_chapter/tput_1.html tput.

+4

:

cols=$(tput cols)
lines=$(tput lines)
numcols=$(((cols-6)/2))
numlines=$((lines/2))

while true; do
    clear
    tput setaf $((RANDOM%8))
    hour=$(date +%H)
    minute=$(date +%M)
    second=$(date +%S)
    hour_binary=$(echo "ibase=10;obase=2;$hour" | bc)
    minute_binary=$(echo "ibase=10;obase=2;$minute" | bc)
    second_binary=$(echo "ibase=10;obase=2;$second" | bc)
    tput cup $numlines $numcols
    printf "%06d\n" "$hour_binary"
    tput cup $((numlines+1)) $numcols
    printf "%06d\n" "$minute_binary"
    tput cup $((numlines+2)) $numcols
    printf "%06d" "$second_binary"
    tput cup $((numlines+3)) $numcols
    sleep 1
done

ansi, tput .

+2

All Articles