我有一个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设置。我试着用两种方法来纠正这一点。
- 退出前添加
tput reset
命令 - 在子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
,没有-C
或bash -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 "