我为 VT100(通常由 Linux/Unix 终端仿真器管理)等终端使用 ANSI 转义序列编写了一个运行良好的函数。 我在下面报告了 Bash 代码。 除了粗略的图形结果之外,另一个问题是如果/直到框本身没有到达输出屏幕的底部,则在框下打印一些空行(取决于消息的行号)。 这是我尝试过的:
#!/bin/bash
# Returns the line number if <= 255; otherwais 255.
function getCurPos() {
local CURPOS
local -i lineNumb
echo -e "\E[6n"; read -sdR CURPOS; CURPOS=${CURPOS#*[}
CURPOS=(${CURPOS//;/ })
#echo ${CURPOS[*]}
lineNumb=${CURPOS[0]}
if [ $lineNumb -gt 255 ]; then
return 255
fi
return $lineNumb
}
# $1: text with "echo -e" interpreted syntax ('\n' means "return")
function messagetBox() {
unset IFS
if [ -z $1 ]; then exit 0; fi
local text=$1
local -i maxLineLenght=0
local -i lineLenght=0
local -i lineNumb=0
local -i count
local -i line
#echo -e "\033[1;31m"
echo
while read i; do
echo -e "| $i ";
lineLenght=${#i}
lineLenght+=4
if [ $lineLenght -gt $maxLineLenght ]; then
maxLineLenght=$lineLenght
fi
lineNumb+=1
done < <(echo -e $text)
count=$maxLineLenght
while [ $count -gt 0 ]; do
echo -en "-"
count+=-1
done
#echo -en "\033[u"
echo -en "\033[$((lineNumb+2))A\n"
count=$maxLineLenght
while [ $count -gt 0 ]; do
echo -en "-"
count+=-1
done
echo -en "\033[1B"
count=$lineNumb
while [ $count -gt 0 ]; do
getCurPos
line=$?
echo -e "\033[${line};${maxLineLenght}H|"
count+=-1
done
echo -en "\033[${lineNumb}B"
echo -e "\033[0m"
}
使用示例:将上面的代码保存到文件sample.sh中,
~$ source ./sample.sh
~$ messagetBox "Hello\nMy name is Lorenzo, I was born in Italy."
--------------------------------------------
| Hello |
| My name is Lorenzo, I was born in Italy. |
--------------------------------------------
~$
有人可以建议我一种更好的方法,或者参考 bash 脚本存储库,我可以在其中找到类似的东西吗?
这里有一个更好的绘制盒子的方法:
$ cat ./messagetBox
#!/usr/bin/env bash
# printf will expand `\n` to newline and `\t1 to tab then `pr`
# will convert any tabs to the appropriate number of blanks.
printf '%b\n' "$*" |
pr -e -t |
awk '
{
width = length($0)
maxWidth = ( width > maxWidth ? width : maxWidth )
lines[NR] = $0
}
END {
dashes = sprintf("%*s", maxWidth + 4, "")
gsub(/ /,"-",dashes)
print dashes
for ( lineNr=1; lineNr<=NR; lineNr++ ) {
printf "| %-*s |\n", maxWidth, lines[lineNr]
}
print dashes
}
'
$ ./messagetBox "Hello\nMy name is Lorenzo, I was born in Italy."
--------------------------------------------
| Hello |
| My name is Lorenzo, I was born in Italy. |
--------------------------------------------
从你的问题中不清楚你使用所有这些转义序列的目的,但如果需要的话,只需将它们添加到输出中即可。