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.
- Add a
tput resetcommand before exiting - 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
}
You output tput sgr0. I would do:
Or "more advanced":
It is odd that you are using
bash -C,-CsetsCflag in$-, which disallows overwritingan existing file with the >, >&, and <> redirection operators, see Bash manual aboutsetbuiltin command. Justbash, without-C, orbash -s <arg> <arg2>.