Shell:呈现数据

1. 标准文件描述符

Linux系统将每个对象当作文件处理。这包括输入和输出进程。Linux用文件描述符(file descriptor)来标识每个文件对象。文件描述符是一个非负整数,可以唯一标识会话中打开 的文件。每个进程一次最多可以有九个文件描述符。出于特殊目的,bash shell保留了前三个文 件描述符(0、1和2)

在这里插入图片描述

1.1 重定向

STDIN

shell从STDIN 文件描述符对应的键盘获得输入,在用户输入时处理每个字符。

在使用输入重定向符号(<)时,Linux会用重定向指定的文件来替换标准输入文件描述符。 它会读取文件并提取数据,就如同它是键盘上键入的。

$ cat < testfile
This is the first line.
This is the second line.
This is the third line.
STDOUT

STDOUT文件描述符代表shell的标准输出。

$ ls -l > test2
$ cat test2
total 20
-rw-rw-r-- 1 rich rich 53 2014-10-16 11:30 test
-rw-rw-r-- 1 rich rich  0 2014-10-16 11:32 test2
STDERR

shell通过特殊的STDERR文件描述符来处理错误消息。STDERR文件描述符被设成2

$ ls -al badfile 2> test4
$ cat test4
ls: cannot access badfile: No such file or directory
$
重定向错误和数据

如果想重定向错误和正常输出,必须用两个重定向符号。需要在符号前面放上待重定向数据 所对应的文件描述符,然后指向用于保存数据的输出文件。

$ ls -al test test2 test3 badtest 2> test6 1> test7
$ cat test6
ls: cannot access test: No such file or directory
ls: cannot access badtest: No such file or directory
$ cat test7
-rw-rw-r-- 1 rich rich 158 2014-10-16 11:32 test2
-rw-rw-r-- 1 rich rich   0 2014-10-16 11:33 test3
$

另外,如果愿意,也可以将STDERRSTDOUT的输出重定向到同一个输出文件。为此bash shell 提供了特殊的重定向符号&>

$ ls -al test test2 test3 badtest &> test7
$ cat test7
ls: cannot access test: No such file or directory
ls: cannot access badtest: No such file or directory
-rw-rw-r-- 1 rich rich 158 2014-10-16 11:32 test2
-rw-rw-r-- 1 rich rich   0 2014-10-16 11:33 test3
$

1.2 永久重定向 exec

可以在脚本执行过程中重定向STDOUT。

$ 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命令来将发给STDERR的输出重定向到文件testerror。接下来,脚本用 echo语句向STDOUT显示了几行文本。随后再次使用exec命令来将STDOUT重定向到testout文 件。注意,尽管STDOUT被重定向了,但你仍然可以将echo语句的输出发给STDERR,在本例中还 是重定向到testerror文件。

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值