-2

What does the following command do exactly?

cat >file.c << EOF
C line
EOF

Will this just create an empty C file named "file.c", and then the following line will be the content of it?

Jens
  • 69,818
  • 15
  • 125
  • 179
EL_9
  • 404
  • 2
  • 10
  • Does this answer your question? [How does "cat << EOF" work in bash?](https://stackoverflow.com/questions/2500436/how-does-cat-eof-work-in-bash) – Rob Evans Nov 04 '20 at 11:27
  • Yes, exactly how you describe, because redirections are strictly processed left-to-right. In the bash manual: https://www.gnu.org/software/bash/manual/bash.html#Redirections – glenn jackman Nov 04 '20 at 13:11
  • `cat >file.c` will, if the file already exists, truncate the file to zero bytes (unless the shell setting "noclobber" is on: `set -C` or `set -o noclobber`). – glenn jackman Nov 04 '20 at 13:13

1 Answers1

0

The technical term for this shell construct is a Here Document ("here" as in "the data is here in this script"). If you had only cat >file.c then stdin would be read until an end-of-file condition (on Unix typically CTRL-D) is met. The result would be written to file.c.

The << EOF part now instructs the shell to pass the following lines on stdin to cat (instead of connecting stdin to the terminal). The shell recognizes the EOF on a line by itself as the end marker. The details are in your shell manual, e.g. for bash it is this paragraph:

Here Documents
   This type of redirection instructs the shell to read input from  the  current  source
   until  a  line  containing  only  word (with no trailing blanks) is seen.  All of the
   lines read up to that point are then used as the standard input for a command.

   The format of here-documents is:

          <<[-]word
                  here-document
          delimiter

   No parameter expansion,  command  substitution,  arithmetic  expansion,  or  pathname
   expansion  is performed on word.  If any characters in word are quoted, the delimiter
   is the result of quote removal on word, and the lines in the  here-document  are  not
   expanded.   If  word  is  unquoted,  all  lines of the here-document are subjected to
   parameter expansion, command substitution, and arithmetic expansion.  In  the  latter
   case,  the  character sequence \<newline> is ignored, and \ must be used to quote the
   characters \, $, and ‘.

   If the redirection operator is <<-, then all leading tab characters are stripped from
   input  lines  and  the  line containing delimiter.  This allows here-documents within
   shell scripts to be indented in a natural fashion.
Jens
  • 69,818
  • 15
  • 125
  • 179