shell基础知识之 stdin,stdout,stderr和文件描述符

stdin,stdout,stderr

stdin=0
stdout=1
stderr=2node

使用tee来传递内容,把stdout 做为stdin 传到下个命令编程

root@172-18-21-195:/tmp/pratice# echo "who is this" | tee -  # -至关于传入到stdout,因此打印2次
who is this
who is this
root@172-18-21-195:/tmp/pratice# echo "who is this" | tee - | cat -n  # cat -n 是显示行数
     1  who is this
     2  who is this

把stderr给导入指定地方编程语言

root@172-18-21-195:/tmp/pratice# ls asdf out.txt 2>/dev/null  1>/dev/null  
root@172-18-21-195:/tmp/pratice# ls asdf out.txt &>out.txt  # 能够简写成这样,也能够写成2>&1 这样,二选一
root@172-18-21-195:/tmp/pratice# cat out.txt
ls: cannot access asdf: No such file or directory
out.txt
1. 将文件重定向到命令

借助小于号(<),咱们能够像使用stdin那样从文件中读取数据:this

$ cmd < file
2. 重定向脚本内部的文本块

能够将脚本中的文本重定向到文件。要想将一条警告信息添加到自动生成的文件顶部,能够
使用下面的代码:code

root@172-18-21-195:/tmp/pratice# cat << EOF >log.txt
> this is a test for log.txt
> EOF
root@172-18-21-195:/tmp/pratice# cat log.txt
this is a test for log.txt

出如今cat < log.txt与下一个EOF行之间的全部文本行都会被看成stdin数据。
log.txt文件的内容显示以下:
dns

3. 自定义文件描述符

文件描述符是一种用于访问文件的抽象指示器(abstract indicator)。存取文件离不开被称为
“文件描述符”的特殊数字。 0 、 1 和 2 分别是 stdin 、 stdout 和 stderr 预留的描述符编号。
exec 命令建立全新的文件描述符。若是你熟悉其余编程语言中的文件操做,那么应该对文
件打开模式也不陌生。经常使用的打开模式有3种。内存

  1. 只读模式。
  2. 追加写入模式。
  3. 截断写入模式。
    < 操做符能够将文件读入 stdin 。 > 操做符用于截断模式的文件写入(数据在目标文件内容被
    截断以后写入)。 >> 操做符用于追加模式的文件写入(数据被追加到文件的现有内容以后,并且
    该目标文件中原有的内容不会丢失)。文件描述符能够用以上3种模式中的任意一种来建立。

建立一个用于读取文件的文件描述符input

[root@dns-node2 tmp]# cat input.txt
aaa
bbb
ccc

[root@dns-node2 tmp]# exec 3<input.txt  # 建立一个新的描述符3, 3和<和input.txt之间千万不能有空格,必须紧挨着。
[root@dns-node2 tmp]# cat <&3
aaa
bbb
ccc

若是要再次读取,咱们就不能继续使用文件描述符 3 了,而是须要用 exec 从新建立一个新的
文件描述符(能够是 4 )来从另外一个文件中读取或是从新读取上一个文件。
建立一个用于写入(截断模式)的文件描述符:cmd

[root@dns-node2 tmp]# exec 4>output.txt
[root@dns-node2 tmp]# echo newline >&4  # &在这里能够理解为获取4这个FD的内存地址(我的理解,该理解来自go语言)
[root@dns-node2 tmp]# cat output.txt
newline

追加模式test

[root@dns-node2 tmp]# exec 5>>input.txt
[root@dns-node2 tmp]# echo Append line >&5
[root@dns-node2 tmp]# cat input.txt
aaa
bbb
ccc
Append line
相关文章
相关标签/搜索