”Linux之数据呈现“

mark

重定向

bash shell保留了前三个文件描述符(0、1、2),分别表示标准输入、标准输出、标准错误。如果需要将标准输出和标准错误重定向到同一个输出文件中,bash shell提供了特殊的重定向符&>

脚本中重定向输出

临时重定向

在重定向到文件描述符时,必须在文件描述符数字前加一个&

$ cat test8
#!/bin/bash
# testing STDERR messages
echo "This is an error" >&2
echo "This is normal output"
$ ./test8 2> test9
This is normal output
$ cat test9
This is an error

永久重定向

可以在脚本中用exec命令告诉shell在脚本执行期间重定向某个特定文件描述符

$ cat test11
#!/bin/bash
# redirecting output to different locations
exec 2>testerror
echo "This is the start of the script"
echo "now redirecting all output to another location"
exec 1>testout
echo "This output should go to the testout file"
echo "but this should go to the testerror file" >&2
$
$ ./test11
This is the start of the script
now redirecting all output to another location
$ cat testout
This output should go to the testout file
$ cat testerror
but this should go to the testerror file

脚本中重定向输入

exec命令允许将标准输入重定向到Linux系统上的文件

exec 0< testfile

这个命令会告诉shell应该从文件testfile中获得输入而不是STDIN

$ cat test12
#!/bin/bash
# redirecting file input
exec 0< testfile
count=1
while read line
do
echo "Line #$count: $line"
count=$[ $count + 1 ]
done
$ ./test12
Line #1: This is the first line.
Line #2: This is the second line.
Line #3: This is the third line.

消息记录

tee命令相当于管道的一个T型接头,它将从STDIN过来的数据同时发往两处,一处是STDOUT,另一处是tee命令行指定的文件名

$ date | tee testfile
Sun Oct 19 18:56:21 EDT 2014
$ cat testfile
Sun Oct 19 18:56:21 EDT 2014

tee命令在默认条件下会每次覆盖输出文件内容,如果需要追加数据到文件中,可以用-a参数

Researcher

I am a PhD student of Crop Genetics and Breeding at the Zhejiang University Crop Science Lab. My research interests covers a range of issues:Population Genetics Evolution and Ecotype Divergence Analysis of Oilseed Rape, Genome-wide Association Study (GWAS) of Agronomic Traits.

comments powered by Disqus