Shell 输入/输出重定向

stdin输入可以从键盘,也可以从文件得到

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

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

文件描述符

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

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

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

输出重定向实例

复制代码
#默认情况下,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
[root@st ~]# cat xx.txt
ls: wrongfile: No such file or directory 
ks.cfg

#将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
复制代码

 

原文地址:https://www.cnblogs.com/sea-stream/p/9882092.html