Home > OS >  How to reset tput text decoration and color
How to reset tput text decoration and color

Time:08-25

I have a bash script and I want to be able to highlight critical errors when they occur. To that end I wrote the simple function below

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

The problem with this code is that the terminal keeps the tput settings after the script exits. I have tried rectifying this in two ways.

  1. Add a tput reset command before exiting
  2. Execute the commands in a subshell

Option 1 doesn't work because it clears the terminal completely, even with the -x option.

Option 2 doesn't seem to have any effect, the terminal remains changed even after returning to the main shell. My option 2 code looks like this

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

CodePudding user response:

You output tput sgr0. I would do:

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

Or "more advanced":

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

It is odd that you are using bash -C, -C sets C flag in $-, which disallows overwriting an existing file with the >, >&, and <> redirection operators, see Bash manual about set builtin command. Just bash, without -C, or bash -s <arg> <arg2>.

CodePudding user response:

@richbai90 as a simpler alternative for having colored text output without additional packages, please also take a look at:

PS. Please let me know if you liked that.

  • Related