Saturday, February 5, 2011

Detect if shell script is running through a pipe

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.)

  • 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
    
    From dmckee
  • 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"

    From Beano
  • 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
    

0 comments:

Post a Comment