I've looked online for an answer to this but haven't been able to find any answer around this (looking up bash and color yields results for a lot of other color related things).
What I would like to do is implement a --color=(never|always|auto) argument in my own bash scripts similar to the option in ls, grep or other commands. I've never understood how the auto option works under the covers to tell if the output of a command is being piped or redirected.
I'm thinking of an example something like this:
example.sh
#!/bin/bash
text="This is some text"
if [[ "$1" == "--color=always" ]]; then
echo -e "\e[1;36m${text}\e[0m" # light blue
elif [[ "$1" == "--color=never" ]]; then
echo "$text"
elif [[ "$1" == "--color=auto" ]]; then
if [ Being Redirect or Piped ]; then
echo "$text"
else
echo -e "\e[1;36m${text}\e[0m" # light blue
fi
fi
I've done some testing, if I specify color codes in a string that I echo then when it is piped/redirected the color codes will also get piped/redirected (the behaviour we'd expect with --color=always). Additionally if I don't place color codes in my echoed text this is the behaviour I would expect from --color=never (obviously). What I can not figure out is how to get something like --color=auto to work which is aware of pipes and redirects; something that function like the following:
./example.sh --color=auto
=> This is some text # Entire string is colored light blue
./example.sh --color=auto | grep "text"
=> This is some text # Piped text isn't colored so only "text" ends up colored from the grep command (if grep is set to color it)
I'm not sure how to implement this (or if it is even possible) and googling has been unhelpful so far. I'm not sure if this helps or is relevant but I am a linux user (Ubuntu) and use a terminal with xterm-256color, I'm not concerned about portability right now but would be curious for any solutions if there are limitations on the types of terminals it will work on. Any guidance on this would be really appreciated.