In linux, how can I test whether the output of a program is going to a live terminal or to a file?

When you use git it seems to magically know whether standard out is going through a pipe or into a file vs when it is being displayed to the console. For example, if you have colors enabled and you do

git status

it will colorize the output for different categories of files being listed. However, if you do

git status | less


git status > status.txt

it removes the linux color formatting and you only see plain, uncolored text.

How does git detect whether the output of its commands are going to file vs going to the terminal?

-------------Problems Reply------------

isatty(int fd) will check whether the fd refers to a terminal or something else. It's part of unistd.h in the GNU C library.

Man page:

As an aside: if you want to read from a program using another program, but you want to fool isatty into thinking that your program is a human, there is a way to do that. You can use a pseudo-terminal (pty). This technique is used by expect, for example.

This is a C Code to demonstrate how to detect if standard output is redirected:

int main(int argc, char **argv){
if (!isatty(fileno(stdout))){
fprintf(stdout, "argv, argc, someone is redirecting me elsewhere...\n");
return 1;
/* rest of C code here... */

That is how git knows whether the output is going to the terminal or to a file.

Hope this helps, Best regards, Tom.

Can confirm that's what git relies on:

$ grep -ir "isatty" ./*
./builtin-commit.c: if (isatty(0))
./builtin-config.c: stdout_is_tty = isatty(1);
./builtin-pack-objects.c: progress = isatty(2);
./builtin-prune-packed.c: int opts = isatty(2) ? VERBOSE : 0;
./builtin-revert.c: if (isatty(0))
./builtin-shortlog.c: if (!nongit && ! && isatty(0))
./builtin-unpack-objects.c: quiet = !isatty(2);
./color.c: stdout_is_tty = isatty(1);
./compat/winansi.c: if (!isatty(fileno(stream)))
./compat/winansi.c: if (!isatty(fileno(stream)))
./pack-redundant.c: if (!isatty(0)) {
./pager.c: if (!isatty(1))
./pager.c: if (isatty(2))
./remote-curl.c: options.progress = !!isatty(2);
./transport.c: args.no_progress = args.quiet || (!transport->progress && !isatty(1));
./transport-helper.c: int no_progress = v < 0 || (!t->progress && !isatty(1));
./wt-status.c: * will have checked isatty on stdout).

Run against the git source tree.

Note that fds 0=stdin, 1=stdout, 2=stderr by default, but these can of course be re-directed or closed (typically if you are a daemon you close your file descriptors and re-open the ones you want).

From a shell script, use the -t test flag applied to the file descriptor 0 (standard input).


# Any Bourne-style shell
[ -t 0 ] && echo This is a terminal

# Modern interactive shells: ksh, bash, zsh
[[ -t 0 ]] && echo This is a terminal

Category:linux Views:1 Time:2010-01-26

Related post

  • Linux Restarting the network from a pthread of a C program 2011-11-16

    We have an application that creates several threads using the pthread library. As we want only the main process to handle certain signals all the pthreads have SIGTERM, SIGINT and SIGHUP blocked. In one of our pthreads we restart the network using sy

  • How can we use the output of a program to make further calculations? C (Linux) 2010-09-03

    When I write code in C, I often get confused when the questions/problems demand the usage of the output for further calculations. For example, if we have to print an array and then add only the prime numbers from it or something which is similar. I g

  • How can I view console output of a program in an editor like emacs or Vim in linux? 2011-09-09

    Lets say I have a simple program : (pseudocode) for(i=0;i<1000;i++) { print(i + "\n"); sleep(1); } Output: 0 1 2 Is there way to view this output in an editor like emacs or Vi as it changes ? The behaviour I want is like "tail -f" done on a file b

  • Boost 1.48 compilation in Linux - get the compiler name in the output files with Bjam? 2011-12-08

    I am trying to compile the Boost 1.48 in CentOS 5.6. I need the files to be in this format: boost_program_options-gcc41-mt-1_48 I am compiling with this bjam flags: ./b2 -q --toolset=gcc --layout=tagged --without-mpi install but it still don't add th

  • Is there any linux tool can find the process trace of a python program? 2012-03-28

    I have a python process running now , but it hangs with no log、no exception, i don't know what's going on with it. This bug turns out every 5 or 6 hours, so this time i don't want to kill the process and trying to find a way to trace which line it ha

  • Linux bash command incorrectly handles zeros in output. 2014-04-01

    I'm using Debian 6-64. When i'm running a command echo -n `cat /proc/$(ps -o pid --no-header -C x-session-manager | tr -d ' ')/environ 2>/dev/null | tr '000' '\n'|grep XA|cut -d '=' -f 2` to acquire XAUTHORITY for the current user logged in, I exp

  • How to show a message box from a bash script in linux 2008-08-10

    I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output. So far the only input required is a password for sudo - and gksudo handles t

  • Why is ¿ displayed different in Windows vs Linux even when using UTF-8? 2008-10-06

    Why is the following displayed different in Linux vs Windows? System.out.println(new String("¿".getBytes("UTF-8"), "UTF-8")); in Windows: ¿ in Linux: ¿ --------------Solutions------------- System.out.println() outputs the text in the system default

  • How does the 'ls' command work in Linux/Unix? 2008-10-15

    I would like to know exactly how the "Is" command works in Linux and Unix. As far as I know, ls forks & exec to the linux/unix shell and then gets the output (of the current file tree. eg./home/ankit/). I need a more detailed explanation, as I am

  • How to start Linux Programming 2008-10-16

    I am working on C++ and COM/ATL in Windows from last few years. Now I want to shift to Linux Programming. I know basic architecture of Linux. I did some of the projects which are using ncurses, sockets and audio libraries(Terminal Applications). On w

  • get command output in pipe, C for Linux 2008-10-20

    I need to run a Linux CLI command and get its stdout output from C. I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to w

  • How to add display a message in linux commandline upon logging in? 2008-10-29

    There are certain messages which i wish to display to the personal who is doing putty to a linux shell. How do i like configure some kind of welcome message when people login to the linux shell? --------------Solutions------------- Message of the day

  • Quickly create a large file on a Linux system? 2008-11-03

    How can I quickly create a large file on a Linux (Red Hat Linux) system? dd will do the job, but reading from /dev/zero and writing to the drive can take a long time when you need a file several hundreds of GBs in size for testing... If you need to d

  • How do I find the file handles that my process has opened in Linux? 2008-11-06

    When we perform a fork in Unix, open file handles are inherited, and if we don't need to use them we should close them. However, when we use libraries, file handles may be opened for which we do not have access to the handle. How do we check for thes

  • What do I use on linux to make a python program executable 2008-11-20

    I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux. --------------Solutions------------- Just put this in the first line of your script : #!/usr/bin/env python Make the file

  • Creating a GUI application that wraps command-line programs on Linux and Windows 2008-12-02

    I'm writing a GUI application that will let users interact with command-line programs. The programs are crystallography programs, in this case. They take a long time to run. There's a certain common workflow using the command-line programs. The outpu

  • printf("something\n") outputs "something " (additional space) (g++/linux/reading output file with gedit) 2008-12-08

    I have a simple C++ program that reads stdin using scanf and returns results to stdout using printf: #include <iostream> using namespace std; int main() { int n, x; int f=0, s=0, t=0; scanf("%d",&n); scanf("%d",&x); for(int index=0; ind

  • Default file extension of the executable created by g++ under Cygwin vs Linux 2008-12-11

    I've done most of my work on VisualStudio and don't have much experience with gcc or g++. When I tried to compile a (ex. aprogram.cpp) this morning on my pc using cygwin, I got (aprogram.exe) when I tried to compile the same thing on my Ubuntu box I

  • C++ ctor question (linux) 2009-01-07

    environment: linux, userspace-application created via g++ from a couple of C++ files (result is an ELF) there is a problem (SIGSEGV) when traversing the constructor list ( __CTOR_LIST__ ) (note: code called via this list is a kind of system initialis

Copyright (C), All Rights Reserved.

processed in 0.094 (s). 11 q(s)