七、标准IO和管道

发布时间 2023-12-04 22:33:51作者: Ju生淮北

七、标准IO和管道

  • 重定向I/O,为什么要进行重定向?可以帮我们解决什么问题?

  • 使用管道符连接命令

1、I/O输入输出

显示器是Linux系统中创建默认的输出设备

I/O:input和output

  • 重定向:将原本标准设备,替换为我们想要的内容

    目的:

    1. 在shell脚本中对脚本输出的内容进行处理,屏蔽不相关的输出信息

    2. 用来清空文件或是向文件里面写入内容,在字符界面将所需的内容保存到指定的文件

    • 输出重定向:将原本输出屏幕的内容输出到文件

      类型:

      • 标准正确输出:>:将屏幕上正确的输出重定向到文件

      • 标准错误输出:2>:将屏幕上错误的输出重定向到文件

      • 全部输出:&>:正确输出和错误输出

        • 重定向覆盖到文件:echo >

        • 重定向追加到文件:echo >>

      将所有不想要的输出内容,无需重定向到文件,而是重定向到 /dev/null(空设备)这个设备

      /dev/null:Linux黑洞文件;垃圾桶;空设备;所有重定向到该文件的内容都不会被保存

 1 [root@example tmp]# id lisi > /tmp/lisi.txt
 2 id: ‘lisi’: no such user
 3 [root@example tmp]# ls 
 4 lisi.txt  zhangsan  zhangsan.txt
 5 [root@example tmp]# id lisi 2> /tmp/lisi.txt 
 6 [root@example tmp]# cat lisi.txt 
 7 id: ‘lisi’: no such user
 8 
 9 [root@example tmp]# id wangwu > /tmp/wangwu.txt 2> /tmp/err.txt
10 [root@example tmp]# cat err.txt 
11 id: ‘wangwu’: no such user
12 
13 [root@example tmp]# id lisi &> /tmp/ok.txt
14 [root@example tmp]# cat ok.txt 
15 id: ‘lisi’: no such user
16 
17 [root@example tmp]# id lisi &> lisi.txt
18 [root@example tmp]# echo hello zhangsan >> lisi.txt 
19 [root@example tmp]# cat lisi.txt 
20 id: ‘lisi’: no such user
21 hello zhangsan
  • 管道符 “ | ”

管道符的出现就是为了更好的处理Linux指令(称之为命令的连接符号)

  1. command 1| command 2:将command 1 输出的结果(标准/正确输出)作为command 2输入的参数

  2. command 1| tee 文件名 | command 3:同时将输出保存到文件和在显示器上显示(同时查看和记录)

 1 [root@example ~]# id zhangsan | grep zhangsan
 2 uid=1001(zhangsan) gid=1001(zhangsan) groups=1001(zhangsan)
 3 [root@example ~]# cat /etc/passwd | grep root
 4 root:x:0:0:root:/root:/bin/bash
 5 operator:x:11:0:operator:/root:/sbin/nologin
 6 [zhangsan@example ~]$ find / -name selinux | tee ok.txt | cat > err.txt
 7 [zhangsan@example ~]$ cat err.txt 
 8 /sys/fs/selinux
 9 /etc/sysconfig/selinux
10 /etc/selinux
  • 重定向输入:

  1. 使用文件作为输入源(tr字符转换): < 标准重定向输入

  2. 模拟从键盘接收多行输入:–stdin(接受标准输入)

  3. 写入配置文件(在脚本中自动生成配置文件): <<

    cat >> 文件路径 << EOF(自定义任意字符)

    文件内容……

    EOF(结束符号)

 1 [root@example tmp]# passwd zhangsan < pwd.txt 
 2 Changing password for user zhangsan.
 3 New password: BAD PASSWORD: The password is shorter than 8 characters
 4 Retype new password: passwd: all authentication tokens updated successfully.
 5 [root@example tmp]# echo redhat | passwd --stdin zhangsan 
 6 Changing password for user zhangsan.
 7 passwd: all authentication tokens updated successfully.
 8 [root@example tmp]# cat >> err.txt <<EOF
 9 > hello rhce
10 > hello wuhan
11 > EOF
12 [root@example tmp]# cat err.txt 
13 hello rhce
14 hello wuhan