Bash

Bash: echo ignores here-documents

Bash terminal

Well, not quite. I mean, if you are trying to use here-documents with the echo command in bash and it seems you are getting an empty line instead, the issue might be that echo is displaying only the first line, and it turns out to be an empty one. Consider the following example:

$ echo < this is not
> the first line
> from bash's perspective
> foo

$

You see, echo is not awesome with multi-line inputs, and in our previous example bash considers an empty string (the characters following echo invocation) to be the first and only line of input. Everything else is ignored by echo. Perhaps the following example can shed some light over the issue:

$ echo < and this line is going to be unceremoniously
> ignored by echo. And of course, this other one
> too. So, after pressing Enter all this will go
> directly into oblivion.
> foo
this-is-actually-the-first-line
$

There are workarounds, of course:

$ echo "Why, then, bother with
> alternatives when we can use
> double quotes?
> "
Why, then, bother with
alternatives when we can use
double quotes?

$

Like this one:

$ foo=5; bar=10;
$ cat < I prefer this one, using the cat command.
> $foo=$foo
> $bar=$bar
> This way you can use single ('') and double ("") quotes without
> worrying about escaping them.
> foo
I prefer this one, using the cat command.
$foo=5
$bar=10
This way you can use single ('') and double ("") quotes without
worrying about escaping them.
$

There you have. Happy bash‘ing.

Tagged , , , ,

Leave a Reply

Your email address will not be published.