bash 将 cat 输出保存到变量中时,所有换行符都将被删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18018359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:06:57  来源:igfitidea点击:

All newlines are removed when saving cat ouput into a variable

linuxbashshellash

提问by MOHAMED

I have the following file

我有以下文件

linux$ cat test.txt
toto
titi
tete
tata

Saving the cat output into a variable will discard the newlines

将 cat 输出保存到变量中将丢弃换行符

linux$ msgs=`cat test.txt`
linux$ echo $msgs
toto titi tete tata

How to keep the output containing the newlines in the variables?

如何在变量中保留包含换行符的输出?

回答by jlliagre

The shell is splitting the msgsvariable so echoget multiple parameters. You need to quote your variable to prevent this to happen:

shell 正在拆分msgs变量,因此echo获取多个参数。您需要引用您的变量以防止发生这种情况:

echo "$msgs"

回答by Alexander Mills

I had this:

我有这个:

echo $(cat myfile.sh) >> destination.sh

that was causing the problem, so I changed it to:

那是导致问题的原因,所以我将其更改为:

cat myfile.sh >> destination.sh

and that worked, lulz

那行得通,lulz

回答by alexis

you can use the redirection "|"

您可以使用重定向“|”

echo | cat test.txt