数据重定向

1,018 阅读3分钟
原文链接: rangaofei.github.io

数据重定向

这一节内容相对比较简单。

首先理解一下linux的标准输入与输出:
|类型|名称|文件描述符|说明
|—|—|—|—
|stdin|标准输入|0|一般是键盘输入
|stdout|标准输出|1|命令执行成功后的正确信息
|stderr|标准错误输出|2|命令执行失败后的错误信息

假如我们不需要再屏幕上输出而是保存到某个文件,那重定向符就有用了,使用它可以将本来在标准输出上的内容存储到某个文件或者文件描述符。

  1. >

当我们执行一个命令时,例如ls,用来显示非隐藏的文件,结果会直接输出到屏幕上。通过重定向符>我们可以将标准输出重定向到某个文件或者文件描述符。

promote:~ rangaofei$ ls > rootlist
promote:~ rangaofei$ cat rootlist
Desktop
Documents
Downloads
...

输出重定向符有以下特性:

  • 文件若不存在,系统会自动创建该文件
  • 文件存在时,先将文件内容清除,然后再写入
  1. >>

使用该符号时,输出内容会追加到文件末尾。

promote:~ rangaofei$ echo "first line" > rootlist 
promote:~ rangaofei$ echo "second line" >> rootlist
promote:~ rangaofei$ cat rootlist
first line
second line

  1. 将输出与错误分离

文件描述符1表示标准输出,在使用>或者>>的时候,默认使用的是标准输出,也就是标准输出会重定向过去,而标准错误将会继续显示在屏幕上。可以使用1>,1>>,2>,2>>将标准错误与输出分离。

promote:~ rangaofei$ cat rootfile rr 1> rootlist 2> rooterr
promote:~ rangaofei$ cat rootlist
this is root file
this should be append > rootfile

promote:~ rangaofei$ cat rooterr
cat: rr: No such file or directory

上例中将获取rootfile和rr文件中的内容,标准输出重定向到rootlist中,标准错误重定向到rooterr。因为rr文件不存在,所以会产生一个标准错误。

  1. 丢弃内容

/dev/null就为我们提供了这样一个功能,他能够将重定向到此的内容全部丢弃,不保存也不显示。

promote:~ rangaofei$ cat rootfile >/dev/null
promote:~ rangaofei$ cat rootfile
this is root file
this should be append > rootfile

  1. 合并错误与输出
表面上这种写法没问题,但是这种写法是错误的,因为这样写会打乱输出顺序,混淆正常的输出。

cat rootfile rr >> rootlist 2>>&1
cat rootfile rr &>list

以上两种写法都是正确的,推荐第一种。
比较简单,不做验证了。

6. `<`
标准输入,会将文件内容输入替代键盘输入重定向到标准输入。

cat > catfile

这里相当于创建了一个文件`catfile`,然后等待键盘输入,输入的内容会存入文件中,然后`ctrl+D`结束输入。现在使用虾米那的命令:

promote:~ rangaofei$ cat > catfile < rootfile
promote:~ rangaofei$ cat catfile
this is root file
this should be append > rootfile

roofile中的内容全部复制到了catfile中。这就是输入重定向。

7. `<<`

这个命令可以输入多行文本。也可以称为`here document`。
```shell
promote:~ rangaofei$ cat >catfile <<EOF
> this is a here document
> you can input several lines
> EOF
promote:~ rangaofei$ cat catfile 
this is a here document
you can input several lines

注意一对EOF之间的内容会全部写入,不需要ctrl+D来结束输入,开头的命令也可以写成cat <<EOF >catfile,推荐这种写法。注意最后输入的EOF必须顶头写,否则会被认为没有结束输入。
cat <<-EOF 会去出输入中的tab,而不会删除空格。