In following command cat takes the content of here-doc and redirects it to file named conf:

cat > conf << EOF

How to understand the order of commands here? Does bash first processes everything else(here-doc part) and as a final step it looks the > conf part?

3 Answers 3


Here-Document is a kind of shell redirection, so the shell will perform it as normal redirection, from beginning to the end (or from left to right, or order of appearance). This's defined by POSIX:

If more than one redirection operator is specified with a command, the order of evaluation is from beginning to end.

In your command, cat will perform > conf first, open and truncate conf file for writing, then reading data from Here-Document.

Using strace, you can verify it:

$ strace -f -e trace=open,dup2 sh -c 'cat > conf << EOF
open("conf", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
dup2(3, 1)                              = 1
dup2(3, 0)                              = 0
  • I see. So basically what happens in case of cat > file_name << blah is that before executing cat the stdout of shell is connected to file named file_name and then stdin of shell is connected to here-doc?
    – Martin
    Commented Jul 3, 2015 at 8:24
  • @Martin: Yes. You can see open was called before dup2.
    – cuonglm
    Commented Jul 3, 2015 at 9:19

Well, let's find out:

unset file
cat >"$file" <<EOF
this is not in ${file=./myfile}

bash: : No such file or directory

Dang. I guess it must be doing the >"$file" part first then. But what if...?

unset file
<<EOF cat >"$file"
this is in ${file=./myfile}

...no error...?

cat ./myfile

this is in ./myfile

As it appears, order matters.


When bash creates the process to run cat, it opens conf for write on file descriptor 1 and opens a temporary file (for the here-document) for read on file descriptor 0, before execing the program. In this case, it doesn't really matter in which order those actions happen.

Order does become significant when file descriptors are reassigned, e.g. with 2>&1.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .