Jim
Jim

Reputation: 14270

Prevent Unix command line from taking on bash color?

I have a Bash script that I run inside of iTerm 2.1.3 on a Mac. I like to use color codes to change the color of the script's output if there's an error:

#!/usr/bin/env bash

database=mydb
RED='\033[0;31m'

echo -e "[Dumping database '$database']"
pg_dump -Fc -v -f /tmp/${database}.bak ${database}
if [ "$?" -ne 0 ]; then
    printf "\n${RED}Database dump failed${NC}\n"
    exit 1
fi

The problem is that if there's an error when I run this script from the Unix command line, then my command line takes on the color of the error output (in this case red) and I have to close the iTerm window to revert back to my usual color. Is there a way to prevent this from occurring inside my script?

Thanks.

Upvotes: 0

Views: 53

Answers (1)

ghoti
ghoti

Reputation: 46826

Whoops! You forgot to set a variable! Your script uses ${NC} to normalize the colour, but its declaration is nowhere to be seen.

You might also want to make the assignments a little prettier using format quotes instead of single quotes.

#!/usr/bin/env bash

database=mydb

if [ -t 0 ]; then
    RED=$'\e[0;31m'
    NC=$'\e[0m'
else
    RED=""
    NC=""
fi

printf "[Dumping database '%s']\n" "$database"
pg_dump -Fc -v -f /tmp/${database}.bak ${database}
if [ "$?" -ne 0 ]; then
    printf "\n${RED}Database dump failed${NC}\n"
    exit 1
fi

Note that I've switched from echo -e to printf, which is more portable (in case you decide you want to run this somewhere that doesn't use bash, but still includes format quotes, like FreeBSD's /bin/sh).

Note also the test, [ -t 0 ] which returns true if it is being run on a terminal. With this condition, the same error output can be used for interactive and logged results, without polluting your logs with control characters.

Upvotes: 2

Related Questions