Search code examples
bashsh

Bash redirections


Could someone please explain the following behavior of bash and if my understanding is correct:

  1. echo abcd > abc def

    the echo abcd prints it out to std out stream, but since due to the presence of ">" it is redirected to the file abc How is def stored as a string in the file abc and not as another file containing the string abcd?

  2. echo abcd > abc > def

    This results in the string abcd to be stored in the file def and the file abc remains empty. How ?

Thanks.


Solution

  • In this command:

    echo abcd > abc def foo bar
    

    Only argument after > is used for output filename and rest is used for echo. Hence you get:

    cat abc
    abcd def foo bar
    

    Then in this command:

    echo abcd > abc > def > xyz
    

    Only the last filename after > will actually the output content and remaining ones will be empty:

    cat xyz
    abcd
    cat def
    cat abc
    

    To store output in multiple output files use tee like this (with suppressed stdout):

    date | tee abc def xyz > /dev/null
    

    Then check content:

    cat abc
    Mon Dec  7 07:34:01 EST 2015
    cat def
    Mon Dec  7 07:34:01 EST 2015
    cat xyz
    Mon Dec  7 07:34:01 EST 2015