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.)
From stackoverflow
hisham_hm
-
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 inbash
), 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
From Dan Moulding
0 comments:
Post a Comment