你好,游客 登录 注册 搜索
背景:
阅读新闻

Shell文件描述符及重定向

[日期:2016-03-23] 来源:Linux社区  作者:scf141592 [字体:大 中 小]

文件描述符是与文件输入、输出相关联的整数。它用来跟踪已经打开的文件。最常见的文件描述符是stdin、stdout、stderr。我们甚至可以将某个文件描述的内容重定向到另一个文件描述符中。文件描述符0,1,2是系统预留的:

0----stdin(标准输入)  1----stdout(标准输出)  2----stderr(标准错误)

实例

(一)、将输出的文本重定向到一个文件中:

[root@localhost shell]# echo "this is a example test"> temp.txt

You have new mail in /var/spool/mail/root

[root@localhost shell]# cat temp

cat: temp: 没有那个文件或目录

[root@localhost shell]# cat temp.txt

this is a example test

[root@localhost shell]# echo this is a example test> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

[root@localhost shell]# echo 'this is a example test'> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

(二)、将文本追加到目标文件

[root@localhost shell]# echo 'this is a example test'>> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

this is a example test

[root@localhost shell]# echo this is a example test>> temp.txt

[root@localhost shell]# cat temp.txt

this is a example test

this is a example test

this is a example test

(三)、cat 文件名 :查看文件的内容

(四)、标准错误的重定向,当命令输出错误信息时,stderr信息就会被打印出来

 [root@localhost shell]# ls +

ls: 无法访问 +: 没有那个文件或目录

[root@localhost shell]# echo $?

2

[root@localhost shell]# ls + > out.txt

ls: 无法访问 +: 没有那个文件或目录

[root@localhost shell]# ls + 2> out.txt

[root@localhost shell]# cat out.txt

ls: 无法访问 +: 没有那个文件或目录


第一次的ls + 中的+是非法参数,因此命令将执行失败;

echo $? 能输出上个命令执行后状态;

第三句的ls + >out.txt将执行失败的信息输出到了屏幕,并不是文件中,最后一句加上文件描述符才输出到了文件中,然后可以查看到文件的内容;

(五)、自定义文件描述符

创建文件描述符进行文件读取;


root@localhost shell]# echo this is s test > input.txt

[root@localhost shell]# exec 3< input.txt

[root@localhost shell]# cat &3

[1] 8171

bash: 3: command not found

[root@localhost shell]# cat 3

cat: 3: 没有那个文件或目录

 

[1]+  Stopped                cat

[root@localhost shell]# cat <&3

this is s test

Linux Shell脚本 多线程  http://www.linuxidc.com/Linux/2015-10/123993.htm

cat命令利用Linux重定向合并文件 http://www.linuxidc.com/Linux/2015-01/112122.htm

Shell编程浅析 http://www.linuxidc.com/Linux/2014-08/105379.htm 

Linux Shell参数替换 http://www.linuxidc.com/Linux/2013-06/85356.htm

Shell for参数 http://www.linuxidc.com/Linux/2013-07/87335.htm

Linux/Unix Shell 参数传递到SQL脚本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell脚本中参数传递方法介绍 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell脚本传递命令行参数 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、转义字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-03/129410.htm

linux
相关资讯       shell重定向  Shell文件描述符 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款