linux下shell重定向

来源:互联网 发布:淘宝开店运费怎么弄 编辑:程序博客网 时间:2024/06/10 18:02

举例说明

ls -l > out.file 2>&1 &

解释:
ls -l > out.file //将ls的输出重定向到文件out.file

2>&1 //在shell中,文件描述符通常是:STDIN,STDOUT,STDERR,即:0,1,2,由此可以看出,它将ls -l > out.file在输出过程中产生的错误信息也放在了STDOUT,即:1中,你可以作实验,如果命令产生了错误,那么错误信息也就在out.file中.

其中可能有点奇怪的是&1,既然>左侧的2可以表示STDERR,为什么右侧不能直接使用1呢?

其实,如果右侧直接使用1,会发现错误信息不在out.file,而是在文件1中,所以这里的&起到了类似转义的作用

:~$ sudo ./test1.sh p1 p2 p3 p4 >out.file 2>1:~$ ls1    out.file   test1.sh:~$ cat 1sudo: ./test1.sh: command not found:~$ cat out.file :~$ sudo ./test1.sh p1 p2 p3 p4 >out.file 2>&1:~$ cat 1sudo: ./test1.sh: command not foundiie@Monitor:~$ cat out.file sudo: ./test1.sh: command not foundiie@Monitor:~$ 

因为test1.sh没有执行权限,所以这里会输出错误:sudo: ./test1.sh: command not found

最后的& ,不用说,是放在后台运行.

参考:http://www.linuxsir.org/bbs/thread40501.html