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?
The detection of the output stream type is covered in the question detect if shell script is running through a pipe.
Having decided that you are talking to terminal, then you can use
tput
to retrieve the correct escape codes for the particular terminal you are using - this will make the code more portable.An example script (in
bash
I am afraid, astcsh
is not my forte) is given below.For more information see "
man tput
" and "man terminfo
" - there are all sorts of escape codes to play with.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":
And try it:
I don't use
tcsh
, but there must be a way to redirect your standard output totty
's standard input. If not, useas your test command in your
tcsh
script, check its exit status and you're done.As far as I know, there is no way to determine the final destination of the output of your shell script; the only thing you can do is provide a switch which allows for suppression of control characters in the output.
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: