简体   繁体   English

为什么有人会使用echo为bash或ksh中的变量赋值?

[英]Why would someone use echo to assign values to variables in bash or ksh?

Recently I came across an unusual use of echo to assign variables in a client's ksh scripts. 最近我遇到了一个不寻常的echo用来在客户端的ksh脚本中分配变量。

For example, there are many instances such as the following 例如,有许多实例,例如以下

a='something'
b='else'
c=`echo "${a} ${b}"`

I have been unable to come up with any reason why someone may have done this. 我一直无法想出有人可能做到这一点的任何理由。

Could there be some legacy reason for this? 可能有一些遗留的原因吗? (I've been doing shell for 30+ years, and never before have I seen this) (我已经做了30多年的壳,从来没有见过这个)

Or is it just ignorance? 还是只是无知?

There is no compelling reason whatsoever for this, either in current bash, or its POSIX sh or Bourne predecessors. 无论是在当前的bash还是其POSIX sh或Bourne前辈中,都没有令人信服的理由。

c="$a $b"

...is a complete replacement for the code given, and runs far faster (try putting it in a loop; command substitutions, as created by backticks, fork off a new shell as a subprocess and read its stdout -- a high-overhead operation). ...是给出的代码的完全替代,并且运行得更快(尝试将其置于循环中;命令替换,由反引号创建,将新shell作为子进程分离并读取其stdout - 高开销操作)。

What you saw is an example of bad use of echo because c could be declared as: 你看到的是一个错误使用echo的例子,因为c可以声明为:

c="$a $b"

A common use of echo is when you need comands to filter output, for example 例如,当您需要命令来过滤输出时,回声的常见用途是

$ line="100090 $100,00 Mary"
$ name=`echo "$line" | grep -Eo "[a-zA-Z]+$"`
echo $name
Mary

But it would be more efficient if you don't use echo at all. 但是如果你根本不使用echo会更有效率。 The same thing above can be done with "read", without creating a new process: 上面的相同内容可以通过“read”完成,而无需创建新进程:

$ line="100090 $100,00 Paul"
$ read -r _ _ name _ <<<"$line"
echo $name
Paul

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

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