6

I just wanted to know what is the difference between:

echo {$number1..$number2}

AND

eval echo {$number1..$number2}

Of course, imagine that there is a value in $number1 and $number2. With the first option is just not working, but with the second option it works. I'm not the typical guy that only want something to work, I want to understand why it happens like that so, why exactly is this happening like this?

4

2 回答 2

9

为什么第一个表达式不能按预期工作

  1. 大括号扩展在变量扩展之前执行。$number1..$number2不是一个有效的序列表达式,所以整个表达式保持不变。
  2. 之后,发生变量扩展,产生表达式{1..3}(给定number1=1and number2=3)。

为什么第二个表达式会

您的第二个示例的工作原理相同,只是变量扩展 ( {1..3}) 的结果再次通过 传递给 Bash eval,给大括号扩展第二次机会:1..3是一个正确格式的序列表达式,因此大括号扩展产生预期的结果:

1 2 3

避免使用eval

eval通常应避免使用,因为它很容易引入安全问题:如果number1number2接收输入并且未正确清理,则可以将恶意代码注入您的程序中。有关在各种用例中替换的方法,请参阅此相关问题。eval

在您的具体示例中,可以通过结合算术评估的 for 循环创建序列:

for ((i=number1 ; i<=number2; i+=1)); do echo -n "$i" ; done | xargs
1 2 3

一个流行的非 Bash 解决方案是使用(正如 Walter A 在他的回答seq中指出的那样),如.seq "$number1" "$number2" | xargs

注意:xargs在这些示例中,将多行输出连接到单行。

更多信息

这个对相关问题的回答提供了有关该主题的更多信息。

此外,bash(1) 手册页中的EXPANSION 部分对不同扩展机制的顺序和工作方式提供了相当丰富的信息。

于 2019-02-03T01:20:18.280 回答
0

变量的替换为时已晚。你
可以避免eval

seq -s " " "$number1" "$number2"
于 2019-02-03T10:12:51.573 回答