如何重置tput文本装饰和颜色



我有一个bash脚本,我希望能够在出现关键错误时突出显示这些错误。为此,我在下面写了一个简单的函数

error() {
# set the text decoration
tput -S <<END
bold
setaf 1
END
# echo the error to stderr
echo "$1" 1>&2
exit 1
}

此代码的问题在于,在脚本退出后,终端会保留tput设置。我试着用两种方法来纠正这一点。

  1. 退出前添加tput reset命令
  2. 在子shell中执行命令

选项1不起作用,因为即使使用-x选项,它也会完全清除终端。

选项2似乎没有任何效果,即使在返回到主外壳后,终端仍然保持更改。我的选项2代码看起来像这个

error() {
bash -C <<EOF
tput -S <<END
bold
setaf 1
END
echo "$1" 1>&2
EOF
exit 1
}

输出tput sgr0。我会做:

error() {
tput bold setaf 1 >&2
echo "ERROR: $*" >&2
tput sgr0 >&2
}

或者";更高级":

error() {
tput bold setaf 1
echo "ERROR: $*"
tput sgr0
} >&2

奇怪的是,您使用的是bash -C-C$-中设置了C标志,这不允许覆盖an existing file with the >, >&, and <> redirection operators,请参阅Bash手册中关于set内置命令的内容。只有bash,没有-Cbash -s <arg> <arg2>

一个更简单的替代方案,用于在没有额外包的情况下输出彩色文本。

将以下行复制并粘贴到您的shell中,并调用相应的函数传递所需的消息,您将看到输出有多酷,快速而简单(

:<<'ANSIcolorCodes'
Black        0;30     Dark Gray     1;30
Red          0;31     Light Red     1;31
Green        0;32     Light Green   1;32
Brown/Orange 0;33     Yellow        1;33
Blue         0;34     Light Blue    1;34
Purple       0;35     Light Purple  1;35
Cyan         0;36     Light Cyan    1;36
Light Gray   0;37     White         1;37
ANSIcolorCodes
# # # Just to have unify messages # # #
type echo_blue  echo_green  echo_red  echo_red_s &> /dev/null || {
echo_blue(){
echo -en "33[0;34m$*" ;echo -e "33[0;0m"
}
echo_green(){
echo -en "33[0;32m$*" ;echo -e "33[0;0m"
}
echo_red(){
echo -en "33[0;31m$*" ;echo -e "33[0;0m"
}
echo_red_s(){
echo -en "33[9;31m$*" ;echo -e "33[0;0m"
}
### Due to Update #1
# Define Bold
echo_bold(){ 
echo -en "33[1m$*" ;echo -e "33[0m"; 
}
# Define Blue-Bold, and so on for any other color if needed.
echo_blue_bold(){ echo_blue `echo_bold "$*"`; }
}

参考链接:

  • https://github.com/vrej-ab/quick-functions/blob/main/global-functions/_color-echo.function.sh
    • 请随时查看我的其他公共存储库https://github.com/vrej-ab?tab=repositories

更新#1(2022年9月1日(

这是带有ANSI的echo命令的BOLD语法。

  • echo -e '33[1mYOUR_STRING33[0m'

请检查和测试提供的功能,包括最后更新的代码部分。

最新更新