Saturday, June 26, 2010

» Finding out whether a script is piped

When writing shell scripts, sometimes you need to find out whether your script is being piped into something else (e.g. a pager like less, or just running on the terminal (unpiped). One use case could be to determine whether you want to enable ANSI style colouring of the output or not. Turns out it is really simple to do.

Shell

To do that from a bash script, use [ -t 0 ], which is true when unpiped, and false when piped:
[ -t 0 ] && COLOR=1 || COLOR=0

Perl, others

In other scripting languages (or even in C/C++), where the isatty function is available, use that -- this example being in Perl:
use POSIX 'isatty';
my $color = isatty(STDOUT);

Labels: ,

0 Comments:

Post a Comment

<< Home