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

前端 未结 9 1221
深忆病人
深忆病人 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条回答
  • 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.

    0 讨论(0)
  • 2020-11-22 13:17

    A little extension to the above answers. The trailing > directs the input into the file, overwriting existing content. However, one particularly convenient use is the double arrow >> that appends, adding your new content to the end of the file, as in:

    cat <<EOF >> /etc/fstab
    data_server:/var/sharedServer/authority/cert /var/sharedFolder/sometin/authority/cert nfs
    data_server:/var/sharedServer/cert   /var/sharedFolder/sometin/vsdc/cert nfs
    EOF
    

    This extends your fstab without you having to worry about accidentally modifying any of its contents.

    0 讨论(0)
  • 2020-11-22 13:18

    In your case, "EOF" is known as a "Here Tag". Basically <<Here tells the shell that you are going to enter a multiline string until the "tag" Here. You can name this tag as you want, it's often EOF or STOP.

    Some rules about the Here tags:

    1. The tag can be any string, uppercase or lowercase, though most people use uppercase by convention.
    2. The tag will not be considered as a Here tag if there are other words in that line. In this case, it will merely be considered part of the string. The tag should be by itself on a separate line, to be considered a tag.
    3. The tag should have no leading or trailing spaces in that line to be considered a tag. Otherwise it will be considered as part of the string.

    example:

    $ cat >> test <<HERE
    > Hello world HERE <-- Not by itself on a separate line -> not considered end of string
    > This is a test
    >  HERE <-- Leading space, so not considered end of string
    > and a new line
    > HERE <-- Now we have the end of the string
    
    0 讨论(0)
提交回复
热议问题