bash Shell 脚本:用于输出的 cat 与 echo

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8145657/
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 01:04:19  来源:igfitidea点击:

Shell scripting: cat vs echo for output

bash

提问by Explosion Pills

I've written a small script in bash that parses either the provided files or stdin if no file is given to produce some output. What is the best way to redirect the parsed output to stdout (at the end of the script the result is stored in a variable). Should I use cator echo, or is there another preferred method?

我在 bash 中编写了一个小脚本,如果没有给出文件来生成一些输出,它会解析提供的文件或 stdin。将解析的输出重定向到 stdout 的最佳方法是什么(在脚本末尾,结果存储在变量中)。我应该使用catecho,还是有另一种首选方法?

回答by Keith Thompson

Use the printfcommand:

使用printf命令:

printf '%s\n' "$var"

echois ok for simple cases, but it can behave oddly for certain arguments. For example, echohas a -noption that tells it not to print a newline. If $varhappens to be -n, then

echo对于简单的情况是可以的,但对于某些参数它可能会表现得很奇怪。例如,echo有一个-n选项告诉它不打印换行符。如果$var碰巧是-n,那么

echo "$var"

won't print anything. And there are a number of different versions of echo(either built into various shells or as /bin/echo) with subtly different behaviors.

不会打印任何东西。并且有许多不同版本的echo(内置于各种 shell 或 as /bin/echo)具有微妙不同的行为。

回答by Jarek

echo. You have your parsed data in a variable, so just echo "$var"should be fine. cat is used to print the contents of files, which isn't what you want here.

回声。您将解析的数据放在一个变量中,所以echo "$var"应该没问题。cat 用于打印文件的内容,这不是您在这里想要的。

回答by Michael Hoffman

echois a fine way to do it. You will have to jump through a few hoops if you want catto work.

echo是一个很好的方法。如果你想cat工作,你将不得不跳过几个环节。