tags:

views:

922

answers:

3

How do I detect from within a shell script if its standard output is targetting a terminal or if it's piped to another process? (Case in point: I'd like to add escape codes to colorize output, but only when run interactively, but not when piped, similarly to what ls --color does.)

+16  A: 

Pure bash:

if [ -t 1 ] ; then echo terminal; fi

returns "terminal" and

(if [ -t 1 ] ; then echo terminal; fi) | echo

returns nothing.


The -t flag is described in the man pages as

-t fd True if file descriptor fd is open and refers to a terminal.

and I take advantage of the usual file descriptor assignments

0:     stdin  
1:     stdout  
2:     stderr
dmckee
+6  A: 

The command test (builtin in bash), has an option to check if a file descriptor is a tty.

if [ -t 1 ]; then
    # stdout is a tty
fi

See "man test" or "man bash" and search for "-t"

Beano
+2  A: 

You don't mention which shell you are using, but in Bash, you can do this:

#!/bin/bash

if [[ -t 1 ]]; then
    # stdout is a terminal
else
    # stdout is not a terminal
fi
Dan Moulding