0

Is there a simple way to echo some HTML code into a text/HTML file?

I'm trying to do:

echo "<!DOCTYPE html>\n<html>\n\t<body>\n\t\t<h1>Hello World!</h1>\n\t</body>\n</html>" > index.html

But get:

-bash: !DOCTYPE: event not found
GTS Joe
  • 625

3 Answers3

1

Use single quote as bash interprets ! as a special char

Also, use -e with echo so that the backslash escapes like \n are interpreted

echo -e '<html>\n<html>\n\t<body>\n\t\t<h1>Hello World!</h1>\n\t</body>\n</html>' > index.html
GMaster
  • 6,322
0

You can solve this by using single quotes instead of double-quotes. So, this should work as expected -

echo '<!DOCTYPE html>\n<html>\n\t<body>\n\t\t<h1>Hello World!</h1>\n\t</body>\n</html>' > index.html

When you use single quotes, bash doesn’t try to interpret special characters and simply preserves the literal string.

rubaiat
  • 803
0

You are triggering a history expansion in bash with !. Either turn off history expansions with set +H, use a single quoted string, or use a here-document to write your HTML:

$ cat <<'END_HTML' >index.html
<!DOCTYPE html>
<html>
        <body>
                <h1>Hello World!</h1>
        </body>
</html>
END_HTML

Or, if you want to write out those encoded tabs and newlines as they are:

$ cat <<'END_HTML' >index.html
<!DOCTYPE html>\n<html>\n\t<body>\n\t\t<h1>Hello World!</h1>\n\t</body>\n</html>
END_HTML

History expansions are not triggered within here-documents in bash.

Kusalananda
  • 333,661