目录

shell 文件和重定向

Unix 中每个进程默认拥有 STDIN、STDOUT、STDERR 三个输入输出通道。本文介绍文件重定向的常见用法:输入重定向、文件合并与追加、«EOF heredoc 写法、错误日志重定向到文件,以及 2>&1 合并输出与错误,文末附重定向命令速查表。

Unix中的每个进程默认都可以访问三个输入/输出通道:STDIN(标准输入)、STDOUT(标准输出)和STDERR(标准错误)。

一、 打印myfile中包含单词foo的行

1
grep foo < myfile

二、 文件合并

一般配合文件切割使用

将文件file1、file2 合并至新文件combined

1
cat file1 file2 > combined 

三、 文件追加

1
date >> log

四、 endmarker

要在脚本中从字面上指定STDIN的内容,请使用«endmarker表示法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
cat > file1 <<UNTILHERE
All of this will be printed out.

Since all of this is going into cat on STDIN.

UNTILHERE

# >> 追加
cat >> file1 <<UNTILHERE
All of this will be printed out.

Since all of this is going into cat on STDIN.

UNTILHERE

# 一般使用EOF
cat >> file1 <<EOF
All of this will be printed out.

Since all of this is going into cat on STDIN.

EOF

五、 输出错误日志至文件

1
httpd 2> error.log

六、 chanel 输出类型

STDIN is channel 0, STDOUT is channel 1, while STDERR is channel 2.

1
 grep foo nofile 2>&1 # errors will appear on STDOUT,既正常输出也输出错误日志

七、总结

重定向

command释义
cmd 1> fiel把 标准输出 重定向到 file 文件中
cmd > file 2>&1把 标准输出 和 标准错误 一起重定向到 file 文件中
cmd 2> file把 标准错误 重定向到 file 文件中
cmd 2» file把 标准错误 重定向到 file 文件中(追加)
cmd » file 2>&1把 标准输出 和 标准错误 一起重定向到 file 文件中(追加)
cmd < file >file2cmd 命令以 file 文件作为 stdin(标准输入),以 file2 文件作为 标准输出
cat <>file以读写的方式打开 file