文件描述符 缩写 描述
0 STDIN 标准输入
1 STDOUT 标准输出
2 STDERR 标准错误
1. STDIN
可以来自键盘,可以来自重定向文件输入。
1 [Hermioner@localhost Documents]$ cat
2 a #从键盘输入3 a #输出4 b #从键盘输入5 b #输出6 ^C #ctrl+c强制终止输入
View Code
1 [Hermioner@localhost Documents]$ cat
13 #采用文件重定向输入
View Code
2. STDOUT
1 [Hermioner@localhost Documents]$ ls -l >ltest2 [Hermioner@localhost Documents]$ catltest3 total 32
4 drwxrwxr-x. 2 Hermioner Hermioner 6 Jul 26 02:28a5 -rw-rw-r--. 1 Hermioner Hermioner 0 Jul 28 18:29ltest6 -rw-rw-r--. 1 Hermioner Hermioner 18 Jul 28 18:28test7 -rwxrwxr-x. 1 Hermioner Hermioner 17 Jul 28 06:54test18 -rwxrwxr-x. 1 Hermioner Hermioner 196 Jul 27 21:05 test1.sh
9 -rw-rw-r--. 1 Hermioner Hermioner 97 Jul 28 06:56test210 -rwxrwxr-x. 1 Hermioner Hermioner 144 Jul 28 05:41 test2.sh
11 -rw-rw-r--. 1 Hermioner Hermioner 73 Jul 28 05:46test312 -rwxrwxr-x. 1 Hermioner Hermioner 94 Jul 28 06:17 test3.sh
13 -rwxrwxr-x. 1 Hermioner Hermioner 221 Jul 28 06:08testfile14 [Hermioner@localhost Documents]$15
16
17 #本该到显示器的输出重定向了文件;标准输出就是终端显示器
View Code
1 [Hermioner@localhost Documents]$ lss -l >atest2 bash: lss: command not found...3 Similar command is: 'ls'
4 [Hermioner@localhost Documents]$ catatest5
6 #当错误命令重定向时,发现只会在终端报错,文件中什么内容都没有写入。可以采用STDERR来捕捉错误
View Code
3. STDERR
默认情况下,STDERR和STDOUT是向终端输出,即使重定向也改变不了STDERR的输出去向。比如上面lss命令例子。但是,为了错误情况分离,仍然可以采用如下解决办法来实现:
(1)只重定向错误
根据表中符号总结,STDERROR文件描述符被改为2,就可以只重定向错误了。
1 [Hermioner@localhost Documents]$ lss -l 2>test2 [Hermioner@localhost Documents]$ cattest3 bash: lss: command not found...4 Similar command is: 'ls'
5 [Hermioner@localhost Documents]$
View Code
(2) 重定向数据和错误
数据和错误可以分开放,也可以放在一起。
1 [Hermioner@localhost Documents]$ ls
2 a ltest test1 test2 test3 testfile3 atest test test1.sh test2.sh test3.sh
4 [Hermioner@localhost Documents]$ ls -l test1 test2 y 2> test8 1>test95 [Hermioner@localhost Documents]$ cattest86 ls: cannot access y: No such fileor directory7 [Hermioner@localhost Documents]$ cattest98 -rwxrwxr-x. 1 Hermioner Hermioner 17 Jul 28 06:54test19 -rw-rw-r--. 1 Hermioner Hermioner 97 Jul 28 06:56test210 [Hermioner@localhost Documents]$11
12 #这样错误和数据分别保存在了两个文件中
View Code
4. 输入输出重定向
简单来说,输出重定向就是将本该向命令窗口输出的内容输出到了指定文件中去;输入重定向是本该输入到文件中的内容被弄到了命令窗口。
主要有以下四个:
command > outputfile
command >> outputfile 追加输出
command < inputfile
command << inputfile 追加写入
note:也可以自定义重定向描述符,比如3> file这种形式,指定file这个和符号3匹配的重定向形式。bash shell允许在脚本创建自己的文件描述符。你可以创建文件描述符3-9,并将它们分配给要用到的任何输出文件。一旦创建了文件描述符,你就可以利用标准的重定向符号将任意命令的输出重定向到那里。输入同理。
5. tee ----------消息记录
tee命令便于将输出同时发送给标准输出和日志文件。这样就可以在显示器上显示脚本的消息的同时,又能将它们保存在日志文件中。
1 [Hermioner@localhost Documents]$ date | teetestfile2 Sat Jul 28 19:00:01 PDT 2018
3 [Hermioner@localhost Documents]$ cattestfile4 Sat Jul 28 19:00:01 PDT 2018
5 [Hermioner@localhost Documents]$
View Code
参考文献: