天天看点

shell脚本中的"2< " ">&2" "&>"shell脚本中的"2< " ">&2" "&>"

shell脚本中的"2< " ">&2" "&>"shell脚本中的"2< " ">&2" "&>"

linux标准文件描述符:

文件描述符

缩写

描述

stdin

标准输入

1

stdout

标准输出

2

stderr

标准错误

标准输入和标准输出指的就是键盘和显示器。

当文件描述符(0,1,2)与重定向符号(<)组合之后,就可以重新定向输入,输出,及错误。

command    2>file1

   命令执行的错误信息保存到了file1文件中。显示屏只是显示正确的信息。

command    1>file1  2>file2 

   命令执行后,没有显示。因为正确输出到file1,错误定向到file2

command    &>file1

命令执行后,输出和错误都定向到file1中

在shell脚本中,可以定义“错误”输出到stderr指定的文件.需要在重定向符和文件描述符之间加一个and符(&)

cat test

#!/bin/bash

echo " this is error "   >&2

echo  "this is output"

$

运行脚本

[root@localhost ~]# ./test 2>file1

this is output

[root@localhost ~]# cat file1

this is error

可以再脚本中使用exec命令:

exec 1>file1

exec 2>file2

运行如上脚本,则输出都在file1和file2中。

也可以使用exec 0<file1,从文件1中读取输入。

原文发布时间:2014-07-25

本文来自云栖合作伙伴“linux中国”

继续阅读