linux数据流重定向


1. 标准输入和输出

执行一个命令,有输入,有输出。 标准输入: standard input ,检查 stdin , 代码为0, 使用< 或 << 标准输出: standard output, 简称:stdout . 命令执行返回的正确结果, 代码为1, 使用 > 或 >> 标准错误输出; standard error output. 简称:stderr, 命令执行返回的错误信息。 代码为2, 使用 > 或 >> 默认都输出到屏幕上。

2. 数据流输出重定向

输出默认为屏幕, 可以将输出重定向到文件或其他设备。 使用 > 或 >> > : 表示覆盖写入 >> : 表示追加到原文件末尾,原文件为空则创建文件。
$ find /home -name .bashrc                 
find: /home/lost+found: Permission denied     //stderr
/home/user/.bashrc     //stdout
使用 > 将内容重定向到文件
$ find /home -name .bashrc > std_out 2> std_err
将查询结果写入到std_out文件 将标准错误写入到std_err文件 注意 :2> 或 2>> 中间不能有空格。
/dev/null 目录表示空设备, 写入这儿的内容会被丢弃。 如果不想保存错误信息可以写入/dev/null
$ find /home -name .bashrc > std 2> /dev/null
想把正确和错误的写入一个文件,使用 2>&1 或 &>
$ find /home -name .bashrc > std_out 2>&1
$ find /home -name .bashrc  &> std_out 
一般建议使用第一种写法。

3. 输入重定向

stdin 为键盘输入,使用cat
[work@www sh]$ cat > catfile
hello 
this is from cat .

#按Ctrl+d
[work@www sh]$ 
<为把键盘输入改为文件内容输入
[work@www sh]$ cat > catfile < pass
<< 表示结束输入。
[work@www sh]$ cat > catfile << "eof"
> hello,
> this is from cat 
> eof
[work@www sh]$ cat catfile 
hello,
this is from cat 
[work@www sh]$
当键盘输入eof结束输入,而不必输入Ctrl+d.

相关内容