1.标准的输入和输出
Linux给应用程序提供三种I/O通道
名称 | 描述及默认设备 | 用法 |
standard iuput | 标准输入(STDIN) – 缺省为键盘 | 仅读取 |
standard output | 标准输出(STDOUT) – 缺省为终端窗口,正确的结果 | 仅写入 |
standard error | 标准错误(STDERR) – 缺省为终端窗口 | 仅写入 |
2.输出重定向操作符
标准输出和标准错误能被重定向到文件
command operator filename
命令 操作符 文件名
支持操作符包括:
>file重定向 stdout以覆盖文件
2>file重定向 sterry以覆盖文件
&>重定向所有输出到文件
在重定向时, 缺省是覆盖文件内容.>>符号追加
>> 2>> &>>
2>&1 : 将错误的输出当作正确的输出
/dev/null
示例
以下命令当不做为root用户运行时,产生输出和错误:
$ find /etc –name passwd
可以执行以下操作保存输出和错误信息
$ find /etc –name passwd > find.out
$ find / etc –name passwd 2> /dev/null
$find /etc –name passwd > find.out 2>find.err
3.管道符(|)
管道(|字符)能连接命令:
command1|command2
传送command1的标准输出给command2的标准输入,而不输出到屏幕
结合多个工具的功能
command1 | command2 | command3…等
错误的输出不能通过管道
重定向标准输出一个程序-示例
less:-次查看一个页面的输入
$ Is-l /etc | less
mail:发送输入通过 email
$ echo "test email" | mail -s test user@example.com
lpr:发送输入到打印机
$ echo "test print" | lpr -P printer_name
():结合多个应用程序的 JSTDOUT
$ (cal 2007; cal 2008)| less
三通管道
tee用法
$ command 1 | tee filename | command2
存储 command1的 stdout在 filename里,然后通过管道传给 command2
使用:
・故障诊断复杂的管道
・同时查看和记载输出
输入:默认是终端
tr 'A-Z' 'a-z' < .bash_profile 等价于 cat .bash_profile | tr 'A-Z' 'a-z'
echo redhat | passwd --stdin user1
< :输入来自于文件
command1|command2:作为commnad2的输入
从文件重定向STDIN
・使用<重定向标准输入
・某些命令能接收数据的重定向从文件到标准输入
$ tr 'A-Z' 'a-z' < .bash_profile
・以上命令将把 bash_profile文件中的大写字符全部转换成小写字符
・等效于:$ cat .bash_profile | tr 'A-Z' 'a-z'
发送多行到STDIN
使用<<WORD从键盘重定向多行到 STDIN
接收所有的标准输入直到输入WORD字符
例如
Smail -s "pleaseCall" 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