How to understand "cat > file_name << blah" command?

5,104

Solution 1

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
...

Solution 2

Well, let's find out:

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

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}
EOF

...no error...?

cat ./myfile

this is in ./myfile

As it appears, order matters.

Share:
5,104

Related videos on Youtube

comeback4you
Author by

comeback4you

Updated on September 18, 2022

Comments

  • comeback4you
    comeback4you over 1 year

    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?

  • comeback4you
    comeback4you almost 9 years
    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?
  • cuonglm
    cuonglm almost 9 years
    @Martin: Yes. You can see open was called before dup2.