对stdin,stdout,stderr这三种流进行重定向的形式共有五种:
下面是一个简单的程序
#include<stdio.h> int main(int argc,char *argv[]) { fprintf(stdout,"This is an useless info sent to stdout.\n"); fflush(stdout); fprintf(stderr,"This is an useless info sent to stderr.\n"); return 0; }
./main 1>&2
输出结果为:
bash-4.2@redirection$ ./main 1>&2 This is an useless info sent to stdout. This is an useless info sent to stderr.
第二种情况的写法为:
./main 2>&1
输出结果为:
This is an useless info sent to stdout. This is an useless info sent to stderr.
第三种情况的写法为:
./main 1>outfile
输出结果为:
bash-4.2@redirection$ ./main 1 > outfile This is an useless info sent to stderr. bash-4.2@redirection$ cat outfile This is an useless info sent to stdout. bash-4.2@redirection$
第四中情况的写法为:
./main 2>errfile
输出结果为:
bash-4.2@redirection$ ./main 2>errfile This is an useless info sent to stdout. bash-4.2@redirection$ cat errfile This is an useless info sent to stderr. bash-4.2@redirection$
第五种情况的写法为:
./main 2>errfile 1>&2
或者是:
./main 1>outfile 2>&1
输出结果为:
bash-4.2@redirection$ ./main 1>outfile 2>&1 bash-4.2@redirection$ ./main 2>errfile 1>&2 bash-4.2@redirection$ cat errfile This is an useless info sent to stdout. This is an useless info sent to stderr. bash-4.2@redirection$ cat outfile This is an useless info sent to stdout. This is an useless info sent to stderr.