您的位置:首页 > 运维架构 > Linux

Piping and Redirection,output,Reading from STDIN in script(Linux)

2014-09-08 20:06 429 查看
Every program we run on the command line automatically has three data streams connected to it.

STDIN (0) - Standard input (data fed into the program)
STDOUT (1) - Standard output (data printed by the program, defaults to the terminal)
STDERR (2) - Standard error (for error messages, also defaults to the terminal)




Redirecting to a File

> file_name,将programs output (or whatever it sends to STDOUT)保存在file_name文件中
Exam:
<pre name="code" class="cpp">[yong.chen@entmcnode15] my_linux $ ls > myoutput
[.chen@entmcnode15] my_linux $ cat myoutput
./
../
aa
bb
cc
myoutput
[.chen@entmcnode15] my_linux $ ls
./  ../  aa  bb  cc  myoutput
[.chen@entmcnode15] my_linux $


注意:1.从例中可知,在file myoutput中是一个文件名一行,但在实际terminal中是所有输出文件名都在同一行,所以注意保存在文件中的内容与terminal上输出的相同,但是排版格式可能有所不同。
2.从例中可知,新建的文件myoutput也保存在自身中,所以是先新建输出保存文件,然后将输出内容保存在文件中。
3. > ,是将原文件清空,然后将输出保存其中;若要不清空原文件并保存输出,则使用 >> file_name.


Redirecting from a File

< file_name:与上面内容恰好相反,是将file_name中内容传递到program
[@entmcnode15] my_linux $ wc -l aa
5 aa
[@entmcnode15] my_linux $ wc -l <aa
5
[@entmcnode15] my_linux $ wc -l <aa >output
[@entmcnode15] my_linux $ cat output
5
[@entmcnode15] my_linux $
例中wc -l file_name,是统计file_name中内容的行数。


Piping

| :feed the output from the program on the left of | as input to the program on the right.

ls
barry.txt bob example.png firstfile foo1 myoutput video.mpeg
ls | head -3
barry.txt
bob
example.png
ls | head -3 | tail -1
example.png
解释:将|左边的操作结果传递给| 右边进行操作
line 3:将ls的文件打印前三个
line 7: 选取ls的前三个文件,然后选择此三个文件中的最后一个

Summary:

>
Save output to a file.
>>
Append output to a file, don't clear previous contents
<
Read input from a file.
|
Send the output from one program as input to another program.
Streams
Every program you may run on the command line has 3 streams, STDIN, STDOUT and STDERR.


Reading from STDIN

Bash
accomodates piping and redirection by way of special files. Each process gets it's own set of files (one for STDIN, STDOUT and STDERR respectively) and they are linked when piping or redirection is invoked. Each process gets the following files:

STDIN - /dev/stdin or /proc/self/fd/0
STDOUT - /dev/stdout or /proc/self/fd/1
STDERR - /dev/stderr or /proc/self/fd/2

所以当编写的script要处理pipe的数据,我们只需要read相应的上述三个文件即可。
[@entmcnode15] my_linux $ cat my_script.sh
#!/bin/bash
echo Here is the output
cat /dev/stdin | head -3
[@entmcnode15] my_linux $ cat aa
llkj
da
ds
f
:`k
[@entmcnode15] my_linux $ cat aa | ./my_script.sh
Here is the output
llkj
da
ds
[@entmcnode15] my_linux $
从例中可知,在script中将STDIN 文件当作/dev/stdin
处理。

Conclusion:

read varName
Read input from the user and store it in the variable varName.
/dev/stdin
A file you can read to get the STDIN for the Bash script
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: