linux重定向:2>&1

目录

基本符号含义

/dev/null

重定向到普通文件

多个重定向复用:1>f1 2>f2

多个重定向到一个文件:1>f1 2>1

多个重定向到一个文件

1>f1 2>&1

2>&1 1>f1

参考:


基本符号含义

  • ">":定向去处
  • "/dev/null":空设备文件
  • "0":stdin
  • "1":stdout
  • "2":stderr

/dev/null

重定向到空文件中,也就是说啥也不干了,重定向到此的stdin、stdout和stderr都会罢工。

$ ls
$ touch 1 2 3
$ ls
1  2  3
$ ls >/dev/null
$ ls 1>/dev/null
$ ls 2>/dev/null
1  2  3

重定向到普通文件

$ ls
$ touch f1 f2 f3
$ ls
f1  f2  f3
$ cat f1
$ ls >f1
$ cat f1
f1
f2
f3
$ ls 1>f2
$ cat f2
f1
f2
f3
$ ls 2>f3
f1  f2  f3
$ cat f3

多个重定向复用:1>f1 2>f2

#include 

int main()
{
        fprintf(stdout, "hello1\n");
        fprintf(stderr, "hello2\n");
        return 0;
}

编译一下:然后运行(我的环境是cygwin):

$ gcc main.c -o main
$ ./main.exe
hello1
hello2
$ ./main.exe 1>f1 2>f2
$ cat f1
hello1
$ cat f2
hello2

多个重定向到一个文件:1>f1 2>1

$ ./main.exe 1>f1 2>f1
$ cat f1
hello1

这个因为文件被打开了两次,然后之写入了第一次写入的内容,试着用下面的方法。

多个重定向到一个文件

1>f1 2>&1

$ ./main.exe 1>f1 2>&1
$ cat f1
hello2
hello1

2>&1 1>f1

$ ./main.exe 2>&1 1>f1
hello2
$ cat f1
hello1

就是这样。。。。

参考:

https://blog.csdn.net/GGxiaobai/article/details/53507530

Linux里的2>&1究竟是什么,这篇文章告诉你

 

你可能感兴趣的:(Linux,Shell)