I'm writing a shell script that uses ANSI color characters on the command line.
Example: example.sh
#!/bin/tcsh
printf "\033[31m Success Color is awesome!\033[0m"
My problem is when doing:
$ ./example.sh > out
or
$./example.sh | grep
The ASCII codes will be sent out raw along with the text, mucking up the output and just generally causing chaos.
I'm interested to know if there is a way to detect this so I could disable color for this special case.
I've search the tcsh man pages and the web for a while and have not been able to find anything shell specific yet.
I'm not bound to tcsh, it's our group standard... but who cares?
Is it possible to detect, inside a shell script, if your output is being redirected or piped?
See this previous SO question, which covers bash. Tcsh provides the same functionality with filetest -t 1
to see if standard output is a terminal. If it is, then print the color stuff, else leave it out. Here's tcsh:
#!/bin/tcsh
if ( -t 1 ) then
printf "\033[31m Success Color is awesome!\033[0m"
else
printf "Plain Text is awesome!"
endif
Inside a bourne shell script (sh, bask, ksh, ...), you can feed the standard output to the tty
program (standard in Unix) which tells you whether its input is a tty or not, by using the -s
flag.
Put the following into "check-tty":
#! /bin/sh
if tty -s <&1; then
echo "Output is a tty"
else
echo "Output is not a tty"
fi
And try it:
% ./check-tty
Output is a tty
% ./check-tty | cat
Output is not a tty
I don't use tcsh
, but there must be a way to redirect your standard output to tty
's standard input. If not, use
sh -c "tty -s <&1"
as your test command in your tcsh
script, check its exit status and you're done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With