none
none

Reputation: 12117

marking end of file while redirecting to a file in a non-interactive bash script using cat

I'm trying to redirect a multi-line string to a file. The string contains special chars like quota and looks like this:

import "this"
import "that"
main() {
    println("some text here");
}

I can use echo such as:

echo "import \"this\"
import \"that\"
main() {
    println(\"some text here\");
}" > myfile.txt

The problem with this approach is that I need to escape all quota chars. I thought about using cat to eliminate the need for escaping. It works well in interactive shells so that I can type cat > myfile.txt and then write my string without escaping and then mark the end of file with <control>d.

How can I mark EOF in the script without the actual key sequence <control>d?

Upvotes: 2

Views: 5863

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754550

Use a 'here document':

cat <<'EOF' > myfile.txt
import "this"
import "that"
main() {
    println("some text here");
}
EOF

The quotes around the initial 'EOF' mean "do not expand any shell variables (etc) in the here document".

Upvotes: 8

Related Questions