Have you ever noticed the following scenario:
$ ls File1 file2 file3 file4 file5 $ ls | Cat File1 File2 File3 File4 File5 |
When the LS is executed separately, its output is a line of multiple filenames, and after it is followed by a pipeline, its output becomes a row of a file name, this is why? The principle of this behavior is that the LS program itself can determine (through the Isatty () library function) Its standard output is pointing to a terminal, or something else (pipeline or ordinary file). If the former, the output is one line or more file names, or one output per line.
We can write a simple C program ourselves to demonstrate:
$ cat FOO.C #include <stdio.h> int main () { printf (Isatty (1)? "Terminal \ n": "Non-terminal \ n"); } $ gcc foo.c-o foo $./foo Terminal $./foo | Cat Non-terminal $./foo > File $ cat File Non-terminal |
However, sometimes, we encounter the above situation when we want to save the standard output of a command or give it to other commands to continue processing. For example, git log command, git log directly on the terminal to do is color, git log > Git.log; Cat Git.log; There's no color. This time we need to use the script command, and then use the above-written small program to demonstrate the good:
$./foo | Cat Non-terminal $ SCRIPT-QC./foo | Cat Terminal |
The script command can fool the Foo command so that it thinks its standard output is a terminal. The-c option of the script command is dedicated to this:
-C COMMAND
Run the COMMAND rather than an interactive shell. This makes it-easy-a script to capture the output of a program, behaves differently when its stdout was not a TTY.
In Bash, there is something like the function of the Isatty function in C, which is the-t fd conditional expression:
$ cat foo.sh if [[-T 1]];then Echo terminal; else echo non-terminal; fi $./foo.sh Terminal $./foo.sh | Cat Non-terminal $ SCRIPT-QC./foo.sh | Cat Terminal |
Determine if the standard output points to a terminal