0

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.

5
  • Where are you setting ${NC} ? Commented Feb 1, 2016 at 21:14
  • NC=$'\e[0m' should do it. (add that right below the RED=... line) Commented Feb 1, 2016 at 21:15
  • @DavidC.Rankin, I suspect you meant NC=$'\e[0m' ... format quotes instead of single quotes. Commented Feb 1, 2016 at 21:16
  • Correct you are -- thanks! Commented Feb 1, 2016 at 21:19
  • Thanks guys. I forgot to set NC. @ghoti If you want to make that an answer, I'll give you credit. Commented Feb 1, 2016 at 21:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.