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
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
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.
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
.
\x
sequences are expanded by default andecho -e
outputs-e
(as POSIX currently requires). Useprintf
instead to get a consistent behaviour. – Stéphane Chazelas May 12 '20 at 06:27