shell命令输入输出重定向

Linux命令的执行过程

首先是输入:stdin输入能够从键盘,也能够从文件获得html

命令执行完成:把成功结果输出到屏幕,stout默认是屏幕this

命令执行有错误:把错误也输出到屏幕上面,stderr默认也是屏幕spa

文件描述符

标准输入stdin:对应的文件描述符是0,符号是<和<<,/dev/stdin -> /proc/self/fd/03d

标准输出stdout:对应的文件描述符是1,符号是>和>>,/dev/stdout -> /proc/self/fd/1code

标准错误stderr:对应的文件描述符是2,符号是2>和2>>,/dev/stderr -> /proc/self/fd/2htm

输出重定向实例

#默认状况下,stdout和stderr默认输出到屏幕
[root@st ~]# ls ks.cfg wrongfile
ls: cannot access wrongfile: No such file or directory
ks.cfg
#标准输出重定向到stdout.txt文件中,错误输出默认到屏幕。1>与>等价
[root@st ~]# ls ks.cfg wrongfile >stdout.txt
ls: cannot access wrongfile: No such file or directory
[root@st ~]# cat stdout.txt 
ks.cfg
#标准输出重定向到stdout.txt,错误输出到err.txt。也可使用追加>>模式。
[root@st ~]# ls ks.cfg wrongfile >stdout.txt 2>err.txt
[root@st ~]# cat stdout.txt err.txt 
ks.cfg
ls: cannot access wrongfile: No such file or directory
#将错误输出关闭,输出到null。一样也能够将stdout重定向到null或关闭 # &1表明标准输出,&2表明标准错误,&-表明关闭与它绑定的描述符
[root@st
~]# ls ks.cfg wrongfile 2>&- ks.cfg [root@st ~]# ls ks.cfg wrongfile 2>/dev/null ks.cfg #将错误输出传递给stdout,而后stdout重定向给xx.txt,也能够重定向给null。顺序为stderr的内容先到xx.txt,stdout后到。 [root@st ~]# ls ks.cfg wrongfile >xx.txt 2>&1 #将stdout和stderr重定向到null [root@st ~]# ls ks.cfg wrongfile &>/dev/null

输入重定向

#从stdin(键盘)获取数据,而后输出到catfile文件,按Ctrl+d结束
[root@st ~]# cat >catfile
this
is
catfile
[root@st ~]# cat catfile 
this
is
catfile
#输入特定字符eof,自动结束stdin
[root@st ~]# cat >catfile <<eof
> this
> is
> catfile
> eof
[root@st ~]# cat catfile 
this
is
catfile

 

参考:http://www.cnblogs.com/chengmo/archive/2010/10/20/1855805.htmlblog

相关文章
相关标签/搜索