How does “cat << EOF” work in bash?

前端 未结 9 1306
深忆病人
深忆病人 2020-11-22 12:24

I needed to write a script to enter multi-line input to a program (psql).

After a bit of googling, I found the following syntax works:

c         


        
9条回答
  •  萌比男神i
    2020-11-22 13:15

    Long story short, EOF marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline. A lot of confusion comes from how cat actually works it seems. You can use cat with >> or > as follows:

    $ cat >> temp.txt
    line 1
    line 2
    

    While cat can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
    Heredoc allows to define your entire input as if you are not working with stdin but typing in a separate text editor. This is what Wikipedia article means by:

    it is a section of a source code file that is treated as if it were a separate file.

提交回复
热议问题