1

When using here documents to write multi-line messages to file, in bash, does it matter in which order we apply the here-document (<<) and output redirect (>) operators?

In other words, is there a difference between the following two approaches?

  1. here-doc first

    cat << my_limit_string > my_file
    line 1
    line 2
    my_limit_string
    
  2. output redirect first

    cat > my_file << my_limit_string
    line 1
    line 2
    my_limit_string
    

In this simple example it does not seem to make a difference, but I wonder if there are cases in which the wrong order would lead to unexpected results.

The bash manual says:

Note that the order of redirections is significant.

And the answers to How to understand "cat > file_name << blah" command? suggest the order could indeed matter.

djvg
  • 111
  • 4
  • 1
    the two are equivalent, difference is a matter of taste or readablilty. – Archemar Feb 02 '21 at 09:15
  • @Archemar: Thanks. I just found [this answer](https://unix.stackexchange.com/a/213579) which suggests the order could matter in some cases. Would you agree? – djvg Feb 02 '21 at 09:23
  • 1
    In some cases. This is not one of those. For example, the order matters in `foo cat > my_file << my_limit_string > my_other_file` - each output redirection is applied in turn and the last one is the one that ultimately applies. For independent redirections the order doesn't matter – muru Feb 02 '21 at 09:44
  • 2
    in case of multiple redirection, or self included/self erased/auto included files, ordr my matter. In case of unique redirection, without self inclusion, order doesn't matter. – Archemar Feb 02 '21 at 10:34

0 Answers0