sh command: exec 2>&1

后端 未结 6 687
名媛妹妹
名媛妹妹 2020-12-24 00:45

What will this command do?

exec 2>&1 
6条回答
  •  死守一世寂寞
    2020-12-24 01:32

    One quite useful application of exec 2>&1 that I have come across is when you want to merge stderr and stdout for several commands separated by semicolons. My particular example happened when I was sending more than one command to popen in PHP and I wanted to see the errors interleaved like you would see if you typed the commands at a shell prompt:

    $ echo hi ; yikes ; echo there
    hi
    -bash: yikes: command not found
    there
    $ 
    

    The following does not merge stderr and stdout except for the last echo (which is pointless because the yikes causes the error):

    echo hi ; yikes ; echo there 2>&1
    

    I can get the merged output the "hard way" as follows:

    echo hi 2>&1; yikes 2>&1; echo there 2>&1
    

    It looks a lot cleaner and less error prone if you use exec:

    exec 2>&1 ; echo hi; echo yikes; echo there
    

    You get the stdout and stderr output nicely interleaved exactly as you would see on the terminal if you executed the three commands separated by a semicolon.

提交回复
热议问题