天天看点

1>&2, 2>&1, &>

进行一个标准输出、标准错误输出分流的试验:

edemon@ubuntu1:~/workspace$ ./test.sh
hello world
./test.sh: line 3: pt: command not found
edemon@ubuntu1:~/workspace$ ./test.sh 1>out 2>err
edemon@ubuntu1:~/workspace$ vim -O out err
2      

现在尝试直接重定向标准错误到标准输出:

​​

​edemon@ubuntu1:~/workspace$ ./test.sh 2>1​

但是很遗憾,出现这样的结果:

​​

​hello world​

接着我们能发现一个新的文本1,并在文件1中发现错误信息。

bash将1当做了一个普通文件。

使用​​

​2 >& 1​

​是为了避免这样的坏事发生。

edemon@ubuntu1:~/workspace$ ./test.sh 2 >& 1
hello world
./test.sh: line 3: pt: command not found
# 或者改成:
edemon@ubuntu1:~/workspace$ ./test.sh 2>/dev/stdout
hello
./test.sh: line 3: pt: command not      

能在2的前面加上&吗?不能,bash会将sh脚本在后台执行。

edemon@ubuntu1:~/workspace$ ./test.sh &2 >& 1
[1] 3497
hello world
./test.sh: line 3: pt: command not found
2: command not found
[1]+  Exit 127      

总结:

1和2是文件描述符,而不是文件,需要加上&告诉bash。

例如:

$ cat read
this is a story about hero
text block

# 创建文件描述符3
$ exec 3<read

$ ls
#没有产生文件3
checkRoot.sh  delete.sh  envi.sh  interc.sh  output.sh  read  read1  strlen.sh  test.sh

$ cat <&3
this is a story about hero
text      

1>&2 意思是把标准输出重定向到标准错误.

2>&1 意思是把标准错误输出重定向到标准输出。

​&>​

​​是​

​2>&1 >​

​的缩写

&>filename 意思是把标准输出和标准错误输出都重定向到文件filename中

例如:

$ cat read 2>&1 > read1
$ cat read1
this is a story about hero
text block

$ cat /dev/null > read1

$ cat read &> read1
$ cat read1
this is a story about hero
text