避开Bash中的'seq'命令?
Avoid the 'seq' command in Bash?
我正在讨论在 Bash 脚本中使用 seq
进行小循环(例如具有 10 次迭代的循环)。
我说,比如,最好这样做
for i in {1..10}
do
echo "Welcome $i times"
done
比使用 seq
for i in $(seq 10)
do
echo "Welcome $i times"
done
写在这里:http://www.cyberciti.biz/faq/bash-for-loop/
我认为短循环使用非内置命令是没用的。例如,性能如何?
当您不知道要执行的范围时,seq
会派上用场:您可以说 seq $a $b
,而不能说 {$a..$b}
.
此外,{}
仅适用于 Bash,因此在 Shell 中您将无法使用它。
也就是说,如果您的目标是 bash,那么使用 {1..10}
肯定会比使用 seq
更快(也更便宜),这很重要。 seq
是外部命令,执行速度较慢。
来自man bash
:
Brace Expansion
Brace expansion is performed before any other expansions, and any
characters special to other expansions are preserved in the result.
It is strictly textual. Bash does not apply any syntactic
interpretation to the context of the expansion or the text between the
braces.
...
Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces specially
when they appear as part of a word, and preserves them in the output.
Bash removes braces from words as a consequence of brace expansion.
For example, a word entered to sh as file{1,2} appears identically in
the output. The same word is output as file1 file2 after expansion
by bash. If strict compatibility with sh is desired, start bash with
the +B option or disable brace expansion with the +B option to the set
command.
我正在讨论在 Bash 脚本中使用 seq
进行小循环(例如具有 10 次迭代的循环)。
我说,比如,最好这样做
for i in {1..10}
do
echo "Welcome $i times"
done
比使用 seq
for i in $(seq 10)
do
echo "Welcome $i times"
done
写在这里:http://www.cyberciti.biz/faq/bash-for-loop/
我认为短循环使用非内置命令是没用的。例如,性能如何?
seq
会派上用场:您可以说 seq $a $b
,而不能说 {$a..$b}
.
此外,{}
仅适用于 Bash,因此在 Shell 中您将无法使用它。
也就是说,如果您的目标是 bash,那么使用 {1..10}
肯定会比使用 seq
更快(也更便宜),这很重要。 seq
是外部命令,执行速度较慢。
来自man bash
:
Brace Expansion
Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.
...
Brace expansion introduces a slight incompatibility with historical versions of sh. sh does not treat opening or closing braces specially when they appear as part of a word, and preserves them in the output. Bash removes braces from words as a consequence of brace expansion. For example, a word entered to sh as file{1,2} appears identically in the output. The same word is output as file1 file2 after expansion by bash. If strict compatibility with sh is desired, start bash with the +B option or disable brace expansion with the +B option to the set command.