文件描述符和重定向

文件描述符是一个打开的文件或数据流相关联的证书

0-------stdin 标准输入

1-------stdout 标准输出

2-------stderr 标准错误

# echo “this is a file” > file.txt //将this is a file 重定向到文件file.txt中

# echo "this is a file 2" >> file.txt //将this is a file2 重定向到文件file.txt中,这种方法会将文本追加到目标文件中

> 会清空文件,相当于 1>

>> 不会清空文件,将新的内容追加到现有文件的末尾,相当于1>>

直接输出错误信息

# ls + > out.txt       //直接输出错误信息,未重定向

ls: cannot access +: No such file or directory

将错误信息重定向

#  ls + 2> out.txt   //将错误信息重定向到out.txt

# cat out.txt 

ls: cannot access +: No such file or directory

将错误信息标准输出同时重定向

# ls + 2>err.out 1>out.txt
# cat err.out out.txt
ls: cannot access +: No such file or directory

或者

# ls + > out.txt 2>&1

或者

# ls + >& out.txt

其妙的tee 

tee可以一方面将数据重定向到文件,另一方面还可以提供一份重定向数据的副本作为后续命令的stdin。

# cat t* | tee out.txt      //标准输出+ 文件输出out.txt
hello
ls: cannot access +: No such file or directory

# cat t* | tee -a out.txt //-a用于追加内容

# echo who is this | tee -  //使用stdin作为命令参数,只需要将-作为命令的文件名参数
who is this
who is this

 

posted on 2015-06-04 22:31  karenwang  阅读(387)  评论(0编辑  收藏  举报

导航