linux中的输入与输出管理(重定向输入,输出,管道符)

    科技2022-08-07  96

    linux中的输入与输出管理

    1 理解什么输入输出的定义1)字符设备2)stdin:标准输入3)stdout:标准正确输出4)stderr:标准错误输出2 如何管理输入1)< #输入重定向2)<< 多行录入3 如何管理系统输出1)输出重定向2)追加3)管道 “|”

    1 理解什么输入输出的定义

    1)字符设备

    字符设备就是显示字符到屏幕上的设备文件

    /proc/pid/fd/

    2)stdin:标准输入

    编号为0 键盘 鼠标 打字机

    3)stdout:标准正确输出

    标号为1

    4)stderr:标准错误输出

    标号为2

    2 如何管理输入

    外界传递到程序中的信息

    1)< #输入重定向

    tr 'a-z' 'A-Z' < test ##把test文件中的内容定向到tr程序中 单行录入

    只是在输出的时候显示,但文件里面的内容并没有改变

    tr 'a-z' 'A-Z' < test ###单行录入 : 把test的内容重定向输入到tr环境中 把原本test的默认环境shell改为指定环境 tr (程序定向到指定环境) tr 进程 shell 进程

    ==清空文件 == >test

    [westos@lzy Desktop]$ cat test hello lzy [westos@lzy Desktop]$ > test [westos@lzy Desktop]$ cat test [westos@lzy Desktop]$

    2)<< 多行录入

    修改westos用户的密码为lzy

    passwd westos<<EOF(字符任意) lzy##此处的lzy不能表示为文件名称只表示lzy字符 lzy EOF (当首字母再次出现表示录入结束)

    3 如何管理系统输出

    1)输出重定向

    >=1> 默认重定向输出正确的2>重定向输出错误的&>所有2>&1将错误输出定向到错误中,在管道符处理的时候可以将错误的一起处理

    find /etc -name passwd > westos.out ##重定向正确输出 到指定文件 find /etc -name passwd 2> westos.out ##重定向错误输出到 指定文件 find /etc -name passwd &> westos.out ##重定向所有输出到指定文件

    注意:重定向管理输出后会覆盖原文件内容 2> /dev/null屏蔽错误输出

    [westos@lzy Desktop]$ find /etc -name passwd 2> /dev/null 屏蔽错误输出 /dev/null 相当于垃圾桶 /etc/pam.d/passwd /etc/passwd

    2)追加

    >>追加正确的输出2>>追加错误的输出&>>追加所有

    find /etc -name passwd >> westos.out ##追加正确输出 find /etc -name passwd 2>> westos.out ##追加错误输出 find /etc -name passwd &>> westos.out ##追加所有输出

    注意:追加和重定向功能类似,但是不会覆盖原文件内容

    3)管道 “|”

    把前一条命令的输出变成输入传递到下一条命令进行操作 注意: 1.管道只处理正确输出

    2.2>&1把编号为2的输入转换到编号为1的输出中

    [westos@lzy Desktop]$ find /etc -name passwd 2>&1 | wc -l 16

    3.tee复制输出到指定位置

    4.管道在一条命令中可以使用多次

    test

    在普通用户下执行命令完成以下操作: 1.查找/etc/下的passwd文件屏蔽错误输出 find /etc -name passwd 2> /dev/null

    2.查找/etc/下的passwd文件正确输出保存到/tmp目录中的westos.out中,错误输出保存到/tmp/目录中的westos.err中 find /etc -name passwd > /tmp/westos.out 2> /tmp/westos.err

    3.查找/etc/下的passwd文件保存所有输出到/tmp目录中的westos.all中并统计输入的行数 find /etc -name passwd 2>&1 | tee /tmp/westos.all | wc -l

    4.查找/etc/下的passwd文件统计输出行数并显示输出内容 [westos@lzy Desktop]$ ps PID TTY TIME CMD 6162pts/2 00:00:00 bash 6291 pts/2 00:00:00 ps

    find /etc -name passwd 2>&1 | tee /dev/pts/2 | wc -l 保存在字符设备中,直接在shell中显示 5.转换/etc/目录中passwd文件中的所有字母为大写并统计文件行数 tr 'a-z' 'A-Z' < /etc/passwd | cat -b tr 'a-z' 'A-Z' < /etc/passwd | tee /dev/pts/2 | wc -l

    7.请用脚本非交互模式编写文件westos.file内容为: hello linux hello westos hello linux westos linux is very nice !!

    [root@lzy ~]# vim westos.sh [root@lzy ~]# sh westos.sh [root@lzy ~]# cat westos.sh cat > westos.file << EOF hello linux hello westos hello linux westos linux is very nice !! EOF [root@lzy ~]# cat westos.file hello linux hello westos hello linux westos linux is very nice !! echo "hello linux hello westos hello linux westos linux is very nice !!" > westos.file
    Processed: 0.014, SQL: 8