➜ ganiks@bash-redirection cat 123
11111111
22222222
33333333
➜ ganiks@bash-redirection cat 123 >> abc
➜ ganiks@bash-redirection echo "one line" >> abc
#当cat不带参数的时候,表示使用标准输入作为输入,这允许在标准输入中键入相关的内容
➜ ganiks@bash-redirection cat >> abc
44444444
55555555
66666666^C # ctrl+C
➜ ganiks@bash-redirection cat abc
11111111
22222222
33333333
one line
44444444
55555555
66666666
参考文档
➜ ganiks@bash-redirection cat > find.sh
find . -name "*" -print -exec grep "555" {} \;
^C
➜ ganiks@bash-redirection sudo chmod +x find.sh
➜ ganiks@bash-redirection ./find.sh
.
grep: .: 是一个目录
./abc
55555555
./nginx-V
./find.sh
find . -name "*" -print -exec grep "555" {} \;
./123
#第一种情况
➜ ganiks@bash-redirection ./find.sh 2>&1 > find1.log
grep: .: 是一个目录
grep: 输入文件 ‘./find1.log’ 同时也作输出
#第一种情况
➜ ganiks@bash-redirection ./find.sh > find2.log 2>&1
#结果1
➜ ganiks@bash-redirection cat find1.log
.
./abc
55555555
./nginx-V
./find.sh
find . -name "*" -print -exec grep "555" {} \;
./123
./find1.log
#结果2
➜ ganiks@bash-redirection cat find2.log
.
grep: .: 是一个目录
./abc
55555555
./nginx-V
./find.sh
find . -name "*" -print -exec grep "555" {} \;
./123
./find1.log
55555555
find . -name "*" -print -exec grep "555" {} \;
./find2.log
grep: 输入文件 ‘./find2.log’ 同时也作输出
0 是 stdin
1 是 stdout
2 是 stderr
➜ ganiks@bash-redirection ./find.sh 2>&1 > find1.log
➜ ganiks@bash-redirection ./find.sh > find2.log 2>&1
这里分析的关键是:一步一步分析,分析一步,输出一步
>find1.log
: 将stdout 再重定向到文件>find2.log
: 将stdout重定向到文件重定向的过程其实很简单,但由于和直观感受不一致,往往导致初学者在这里犯很多错误。 参考文档
基本IO重定向操作
> file
: 将stdout重定向到file>>file
:将标准输出重定向到file,如果file存在,append到文件中,即附加到文件的后面,而不是覆盖文件> | file
: 强制将标准输出重定向到file,即使noclobber设置。当设置环境变量set –o noclobber,将禁止重定向到一个已经存在的文件中,避免文件被覆盖。➜ ganiks@bash-redirection cat >> msgfile <<.
heredoc> this is the text of
heredoc> our message
heredoc> end with .
heredoc> . #这里<<.表明以.为结束。因此无需使用^D,而改用.
➜ ganiks@bash-redirection cat msgfile
this is the text of
our message
end with .
>&-
: 关闭标准输出文件描述符在bash中比较少用,从0开始用户表示进行的数据流,0表示标准输入,1表示标准输出,2表示标注错误输出,其他从3开始。
最为常用的场景是将错误消息输出到某个文件,可以加上2>file 到我们的命令中。
我们来看下面一个脚本的例子:
command > logfile 2>&1 &
>logfile
表示command的标准输出重定向至文件logfile中下面可达到类似的效果:
command 2>&1 | tee logfile &
错误输出同样适用标准输出,通过pipe方式,见他们作为输入执行tee logfile。tee命令将它的标准输入copy至他的标准标准输出以及参数所带的文件中。和上面的命令不一眼这里即会在stdout 和logfile中同时输出。
其他文件描述字的重定向,例如<&n,通常用于从多个文件中读入或者写出。
>&-
,表示强制关闭标准输出