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

前端 未结 9 1317
深忆病人
深忆病人 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:18

    In your case, "EOF" is known as a "Here Tag". Basically < 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 < 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
    

提交回复
热议问题