help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] How to let a command take multiple here-doc?


From: Eduardo A . Bustamante López
Subject: Re: [Help-bash] How to let a command take multiple here-doc?
Date: Sun, 31 May 2015 20:08:22 -0500
User-agent: Mutt/1.5.23 (2014-03-12)

Response inline

On Sun, May 31, 2015 at 07:38:29PM -0500, Peng Yu wrote:
> How to understand why the following code only print b?
> 
> cat <<EOF1 <<EOF2
> a
> EOF1
> b
> EOF2
> 
> It is not clear what the correct output should be based on POSIX.
> 
> http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04

It's the same as here:

    address@hidden:~$ cat <<<a <<<b
    b

Or here:

    address@hidden:~$ echo A > a; echo B > b; cat <a <b
    B

Let's remember some simple rules:

* redirections are applied left to right
* a file descriptor is kind of a "pointer" to a resource. Just *one* resource.
* here-docs in bash are basically temp files with the content of the temp files
being what's between the here-doc "tags" or delimiter tokens.

So, based on these, the 'EOF1' here-doc goes to temp file #1 (tmp1) and 'EOF2'
goes to temp file #2 (tmp2). After bash is done preparing the here-doc files,
it calls the cat command basically like this:

$ cat <tmp1 <tmp2

Now, remember that    foo <bar    is basically    foo 0<bar

So the command is actually:


$ cat 0<tmp1 0<tmp2

Since redirections are applied left to right, first, file descriptor zero for
'cat' "points to" 'tmp1'. Then the second redirection is applied, which then
replaces the current value of file descriptor zero, to be 'tmp2' instead of
'tmp1'.

So in the end, you're executing 'cat' with a file open in its file descriptor
#0 (standard input), which is an open handle to 'tmp2'.

> Also, the above link shows the following example. I am not sure why it
> is usefully to intertwine the heredocs of the two separate commands.
> Does anybody know?
> 
> cat <<eof1; cat <<eof2
> Hi,
> eof1
> Helene.
> eof2

You're asking the wrong question. POSIX is not about what's useful. It's for
what was already implemented in the old shells. So, ask Stephen Bourne on why
the grammar of the shell is like that, if that's a characteristic that goes
back to the original Bourne shell.

It's not bash's responsability to question the un-ambiguous recommendations
from POSIX :-) just to implement that stuff correctly.

I do believe that that syntax is just weird.

-- 
Eduardo Bustamante
https://dualbus.me/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]