Bash – Understanding ‘cat > file_name << blah' Command

bashhere-documentshell

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

cat > conf << EOF
var1="cat"
var2="dog"
var3="hamster"
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?

Best Answer

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
var1="cat"
var2="dog"
var3="hamster"
EOF
'
...
open("conf", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
dup2(3, 1)                              = 1
dup2(3, 0)                              = 0
...
Related Question