Daniyal
Daniyal

Reputation: 99

Can I put into variable and echo at the same time?

I have a script like this:

str=$(echo $'Hello World\n===========\n')
echo "$str"

And it works!

Can I have something like this?

echo str=$(echo $'Hello World\n===========\n')

Upvotes: 0

Views: 296

Answers (3)

Edouard Thiel
Edouard Thiel

Reputation: 6248

In bash there is a variable expansion which might be handy for you :

${newvar=value}

Try for instance this:

$ unset str
$ echo "${str=Hello world}"
Hello world
$ echo "$str"
Hello world

And now with your double line example:

$ unset str
$ echo "${str=$'Hello World\n===========\n'}"
Hello World
===========

$ echo "$str"
Hello World
===========

$

Upvotes: 3

tripleee
tripleee

Reputation: 189948

If I am able to guess what you want, how about doing a tee in the process substitution?

str=$(echo $'Hello world!\n====\n' | tee -a /dev/stderr)

This has the obvious drawback that the output is redirected to standard error.

An earlier version of this answer critiqued code which was subsequently removed from the question. See the edit history if you are curious.

Upvotes: 2

Maxime Chéramy
Maxime Chéramy

Reputation: 18871

I think that using two instructions is better because people will be able to understand it:

str=$(echo $'Hello World\n===========\n'); echo "$str"

Upvotes: 0

Related Questions