bash 如何将脚本输出居中显示在屏幕中间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27239183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to center script output in the middle of the screen?
提问by user3504970
Here i have a binary clock which outputs binary clock in 16 different colors and i am trying to make it appear in center of the screen but cant do it. If you have any suggestions how to do it then please let me know. thanks
在这里,我有一个二进制时钟,它以 16 种不同颜色输出二进制时钟,我试图让它出现在屏幕中央,但不能这样做。如果您对如何操作有任何建议,请告诉我。谢谢
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
回答by redhotspike
If you are referring to 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 命令设置光标位置:
tput cup $CENTERCOL $CENTERROW
See http://www.cyberciti.biz/tips/spice-up-your-unix-linux-shell-scripts.htmlfor an example using tput and https://www.gnu.org/software/termutils/manual/termutils-2.0/html_chapter/tput_1.htmlfor more information about the tput command.
有关使用 tput 和https://www.gnu.org/software/termutils/manual/的示例,请参见http://www.cyberciti.biz/tips/spice-up-your-unix-linux-shell-scripts.html termutils-2.0/html_chapter/tput_1.html有关 tput 命令的更多信息。
回答by Gilles Quenot
What I would do :
我会怎么做:
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
I have replaced hard coded ansi sequences by using tput for the colors too
我也使用 tput 作为颜色替换了硬编码的 ansi 序列