Linux——标准IO和管道

    技术2022-07-17  69

    标准的输入和输出

    进程IO通道(文件描述符) 编号 通过名称 描述 默认设备 用法 0 stdin 标准输入 键盘 仅读取 1 stdout 标准输出 显示器 仅写入 2 stderr 标准错误输出 显示器 仅写入 3+ filename 其他文件 无 读取或者写入

    输出重定向操作符

    “>”如果文件不存在则创建这个文件,并输出这个文件里,如果存在则覆盖以前的内容 “>>” 追加 之前的内容会被保存 “2>&1”将错的作为正确的输出 /dev/null:字符类型文件,可接收任何文件且不占内存

     >file 重定向stdout以覆盖文件

     >>file 重定向stdout以追加到文件

     2>file 重定向stderr以覆盖文件

     2>/dev/null 重定向stderr到/dev/null

     &>file 重定向stdout和stderr以覆盖同一个文件 等同于>file 2>&1

     &>>file 重定向stdout和stderr以追加同一个文件 等同于>>file 2>&1

    重定向输出到文件-示例:

     以下命令当不做为root用户运行时,产生输出和错误: $ find /etc –name passwd find:查找文件 /etc:查找什么下的 –name:以什么方式查找  可以执行以下操作保存输出和错误信息 $ find /etc –name passwd > find.out //输出错的正确的重定向到find.out文件里 $ find /etc –name passwd 2> /dev/null//输出正确的,错误的重定向到文件里 $find /etc –name passwd > find.out 2>find.err //正确的重定向到find.out里,错误的重定向到find.err里 $find /etc –name passwd &>find.all//所有都重定向到find.all文件里 $find /etc –name passwd > find.out 2>&1 //将正确的错的都输出到find.out里 $find /etc –name passwd | wc –l //wc:统计 –l:列出行

    管道符:

    管道:一个命令的结果丢给另一个命令执行,不是所有命令都能接收来自管道的输入 管道也是一种标准输入 管道和重定向不能同时存在  管道(|)能连接命令: command1 | command2 | command3…等  将command1的标准输出作为command2的标准输入,而不输出到屏幕  错误的输出不能通过管道

    重定向标准输出到一个程序-示例:

    less:一次查看一个页面的输入 $ ls –l /etc|less mail:发送输入通过email $ echo “test email” | mail –s “test user@example.com lpr:发送输入到打印机 $ echo “test print” | lpr $ echo “test print” | lpr –P printer_name ():结合多个应用程序的STDOUT $ (cal 2007 ;cal 2008)|less

    三通管道:

    tee命令即可重定向也可通过管道 tee用法 $ command1 | tee filename | command2 存储command1的stdout在filename里,然后通过管道传给command2 使用: 故障诊断复杂的管道 同时查看和记载输出

    从文件重定向STDIN:

     使用<重定向标准输入  某些命令能接收数据的重定向从文件到标准输入: $ tr A-Z a-z<.bash_profile 以上命令将把bash_profile文件中的大写字符全部转换成小写字符 等效于:$ cat .bash_profile | tr ‘A-Z’ ‘a-z’

    发送多行到STDIN:

     使用 <<WORD 从键盘重定向多行到STDIN  接收所有的标准输入直到输入WORD字符  例如: $ mail –s “Please Call” jane@example.com <<END

    HI Jane, Please give me a call when you get in.We may need to do some maintenance on server1 Details when you’re on-site, Boris END

    标准输入 stdin:默认键盘输入 标准输出stdout:默认屏幕 <file输入来着文件 >、>>:可接收文件,设备文件 <<多行输入 | 管道 错误输出: 2>接file 2>> /dev/null |:连接多命令 注意跟>的关系

    Processed: 0.012, SQL: 9