linux各种数据流重定向

来源:互联网 发布:powermill10.0编程步骤 编辑:程序博客网 时间:2024/05/16 14:06
  • > :以覆盖的方法将『正确的数据』输出到指定的文件或装置上

  • 1> :以覆盖的方法将『正确的数据』输出到指定的文件或装置上

  • 1>>:以累加的方法将『正确的数据』输出到指定的文件或装置上

  • 2> :以覆盖的方法将『错误的数据』输出到指定的文件或装置上

  • 2>>:以累加的方法将『错误的数据』输出到指定的文件或装置上

  • <:将原本需要由键盘输入的数据,改由文件内容来取代

  • <<:代表的是『结束的输入字符』

  • <<<:将字符串重定向到stdin。

例如:『我要用 cat 直接将输入的信息输出到 catfile 中, 且当由键盘输入 eof 时,该次输入就结束』,那我可以这样做:

[root@www ~]# cat > catfile << "eof"> This is a test.> OK now stop> eof  <==输入这关键词,立刻就结束而不需要输入 [ctrl]+d[root@www ~]# cat catfileThis is a test.OK now stop
其中eof可以使用其他的任意字符串代替。
还有一个“<<-”,主要是为了在输出是忽略掉语句前面的一个或者多个tab符,看下面的例子:
#!/bin/bash
cat << EOF
     123
     456
EOF
输出为:
     123
     456
如果改成:
#!/bin/bash
cat <<- EOF
      123
      456
EOF
输出为:
123
456
  • 2>& 1:将正确和错误的数据全部写入到指定文件或装置上
例如:
yan@yan-vm:~$ ll /root/ /home/ > result 2>& 1yan@yan-vm:~$ cat result/home/:total 16drwxr-xr-x  4 root       root        4096 Jun  4 13:03 ./drwxr-xr-x 23 root       root        4096 Apr 12 20:43 ../drwx------  2 normaluser normalgroup 4096 Jun  4 13:14 normaluser/drwxr-xr-x 24 yan        yan         4096 Jun  5 06:36 yan/ls: cannot open directory /root/: Permission denied
用户yan无法访问/root,所以Permission denied是错误数据,其他的都是正确的数据。
下面我们来衍生几种用法,大家猜猜看运行结果是什么:
ll /root/ /home/ > result 1>&2
ll /root/ /home/ 2> result 1>&2
ll /root/ /home/ 2>&1 > result 
结果:
yan@yan-vm:~$ ll /root/ /home/ > result 1>&2/home/:total 16drwxr-xr-x  4 root       root        4096 Jun  4 13:03 ./drwxr-xr-x 23 root       root        4096 Apr 12 20:43 ../drwx------  2 normaluser normalgroup 4096 Jun  4 13:14 normaluser/drwxr-xr-x 24 yan        yan         4096 Jun  5 06:36 yan/ls: cannot open directory /root/: Permission deniedyan@yan-vm:~$ cat resultyan@yan-vm:~$
分析:正确的数据合并到错误的数据,将正确的数据写到result中,但是此时正确的数据为空,所以写入到result文件中为空,
将错误的数据(包含正确的数据)显示到屏幕上。

yan@yan-vm:~$ ll /root/ /home/ 2> result 1>&2yan@yan-vm:~$ cat result/home/:total 16drwxr-xr-x  4 root       root        4096 Jun  4 13:03 ./drwxr-xr-x 23 root       root        4096 Apr 12 20:43 ../drwx------  2 normaluser normalgroup 4096 Jun  4 13:14 normaluser/drwxr-xr-x 24 yan        yan         4096 Jun  5 06:36 yan/ls: cannot open directory /root/: Permission denied
分析:正确的数据合并到错误的数据,将错误的数据写到result中,此时错误的数据中包含正确的数据,所以result中包含正确和错误的数据。
将正确的数据写到屏幕上,但是此时正确的数据为空,所以没有任何信息显示在屏幕上。

yan@yan-vm:~$ ll /root/ /home/ 2>&1 > resultls: cannot open directory /root/: Permission deniedyan@yan-vm:~$ cat result/home/:total 16drwxr-xr-x  4 root       root        4096 Jun  4 13:03 ./drwxr-xr-x 23 root       root        4096 Apr 12 20:43 ../drwx------  2 normaluser normalgroup 4096 Jun  4 13:14 normaluser/drwxr-xr-x 24 yan        yan         4096 Jun  5 06:36 yan/yan@yan-vm:~$
分析:2>&1 标准错误拷贝了标准输出的行为,但此时标准输出还是在终端。>result 后输出才被重定向到result,但标准错误仍然保持在终端。


  • <<<
todd@todd-pc:~$ cat <<< "abc"
abc
todd@todd-pc:~$

原创粉丝点击