What does &> do in bash?

原文链接:https://stackoverflow.com/questions/24793069/what-does-do-in-bash

Q:
I was looking at pre-commit hook and discovered the following line because I was wondering why I always got an empy file called 1 in my directory after doing a commit.

git status 2&>1 > /dev/null

I believe the intent was to write the following, and I corrected it.

git status 2>&1 > /dev/null

However, I was curious about what the following syntax does exactly, so I looked up the man page.

git status 2&>1

Here is the man page.

  Redirecting Standard Output and Standard Error
      This  construct allows both the standard output (file descriptor 1) and
      the standard error output (file descriptor 2) to be redirected  to  the
      file whose name is the expansion of word.

      There  are  two  formats  for  redirecting standard output and standard
      error:

             &>word
      and
             >&word
  Of the two forms, the first is preferred.  This is semantically equivalent to

     >word 2>&1

However, this man page implies that the two are equivalent, which does not seem to be the case.

Can someone clarify the man page and explain exactly what is happening with this syntax?

A:
The operators we are using here are:

  • > Syntax: file_descriptoropt > file_name
  • >& Syntax: file_descriptoropt >& file_descriptor
  • &> Syntax: &> file_name

If the file descriptor is omitted, the default is 0 (stdin) for input, or 1 (stdout) for output. 2 means stderr.

So we have:

  • >name means 1>name – redirect stdout to the file name
  • &>name is like 1>name 2>name – redirect stdout and stderr to the file name (however name is only opened once; if you actually wrote 1>name 2>name it’d try to open name twice and perhaps malfunction).

So when you write git status 2&>1, it is therefore like git status 2 1>1 2>1 , i.e.

  • the first 2 actually gets passed as an argument to git status.
  • stdout is redirected to the file named 1 (not the file descriptor 1)
  • stderr is redirected to the file named 1

This command should actually create a file called 1 with the contents being the result of git status 2 – i.e. the status of the file called 2 which is probably “Your branch is upto-date, nothing to commit, working directory clean”, presuming you do not actually track a file called 2.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值