0%

如何在shell中嵌入多行文本(配置文件)

stackoverflow 链接

answer

Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat

1
2
3
4
5
cat << EndOfMessage
This is line 1.
This is line 2.
Line 3.
EndOfMessage

The string after << indicates where to stop.

To send these lines to a file, use:

1
2
3
4
cat > $FILE <<- EOM
Line 1.
Line 2.
EOM

You could also store these lines to a variable:

1
2
3
4
5
read -r -d '' VAR << EOM
This is line 1.
This is line 2.
Line 3.
EOM

This stores the lines to the variable named VAR.

When printing, remember the quotes around the variable otherwise you won’t see the newline characters.

1
echo "$VAR"

Even better, you can use indentation to make it stand out more in your code. This time just add a - after << to stop the tabs from appearing.

1
2
3
4
5
read -r -d '' VAR <<- EOM
This is line 1.
This is line 2.
Line 3.
EOM

But then you must use tabs, not spaces, for indentation in your code.