简体   繁体   English

我可以同时输入变量和回显吗?

[英]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')

In bash there is a variable expansion which might be handy for you : 在bash中,您可以方便地进行变量扩展:

${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
===========

$

If I am able to guess what you want, how about doing a tee in the process substitution? 如果我能够猜出您想要什么,那么在过程替换中做一个tee怎么样?

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. 如果您感到好奇,请参阅编辑历史记录。

我认为使用两个说明会更好,因为人们将能够理解它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM