# shell中的 2>&1
Date: 2019-05-11


### 使用说明：

strace跟踪应用程序时，有标准输出和错误输出，需要将程序执行的输出标准输出和错误输出重定向到一个日志文件中。

strace ./gethostbyname www.baidu.com > gethostbyname.default.log 2>&1  

### 重定向说明：

在shell命令执行前， 输入，输出可以通过特殊符号设置完成重定向（redirected）， 重定向允许命令文件可以复制， 打开，关闭。

复制文件操作符号格式如下

           \[n\]>&word

1\. 如果 n没有指定默认为1 （标准输出）

2\. 如果word没有指定，重定向报错；

3\. 如果word设置 ‘-’   ， 文件标识符 n关闭

4\. 如果n忽略，word也不是数字或‘-’，标准输入，输出重定向都被重定向到word。

### 验证：

####         准备：

echo "hello" >txt1

####         验证：

主要验证一下3，4

3.   cat txt1   > cat.log >&-

cat: standard output: Bad file descriptor

4.  cat txt1 txt2 >&cat.log cat cat.log hello cat: txt2: No such file or directory

### 参考：

[GNU Redirections](https://www.gnu.org/software/bash/manual/html_node/Redirections.html)

         [Understanding Shell Script's idiom: 2>&1](https://www.brianstorti.com/understanding-shell-script-idiom-redirect/)

