击变串联 [英] Bash variable concatenation
问题描述
哪种形式是最有效的?
1)
v=''
v+='a'
v+='b'
v+='c'
2)
v2='a'` `'b'` `'c'
假设可读性都是一模一样的给你,这是一个延伸,将1)意味着创建和在Python扔掉一些字符串immutables(等)或作为一个Java的StringBuffer的缓冲能力的周期性扩张?如何在Bash的内部处理字符串连接?
Assuming readability were exactly the same to you, and that's a stretch, would 1) mean creating and throwing away a few string immutables (like in Python) or act as a Java "StringBuffer" with periodical expansion of the buffer capacity? How are string concatenations handled internally in Bash?
如果2)只是为可读你为1),将反引号产卵子shell和那会是更加昂贵,甚至作为一个潜在的无操作比什么是1做)?
If 2) were just as readable to you as 1), would the backticks spawn subshells and would that be more costly, even as a potential 'no-op' than what is done in 1) ?
推荐答案
好了,最简单,最有效的机制将选择0:
Well, the simplest and most efficient mechanism would be option 0:
v="abc"
第一种机制涉及四个任务。
The first mechanism involves four assignments.
第二个机制是奇怪的(而且是绝对无法读取)。它(标称)运行在两个子壳(两个``
部分)的空指挥和并置的三个常量输出(空字符串)。如果shell只是执行的back-tick命令而不提的是,他们是空的(这不是不合理的,它不会注意到,这是尝试奇怪的事情 - 我不记得看到它在我的$ P $完成pvious30年shell脚本),这绝对是大大慢。
The second mechanism is bizarre (and is definitely not readable). It (nominally) runs an empty command in two sub-shells (the two ` `
parts) and concatenates the outputs (an empty string) with the three constants. If the shell simply executes the back-tick commands without noting that they're empty (and it's not unreasonable that it won't notice; it is a weird thing to try — I don't recall seeing it done in my previous 30 years of shell scripting), this is definitely vastly slower.
因此,给定的唯一的选择(1)和(2),使用的选项(1),但在一般情况下,使用选项(0),如上所示。
So, given only options (1) and (2), use option (1), but in general, use option (0) shown above.
为什么你会被改小建立字符串这样呢?什么是缺少从你的榜样,使原来的code明智但小于显示懂事减少code。
Why would you be building up the string piecemeal like that? What's missing from your example that makes the original code sensible but the reduced code shown less sensible.
v=""
x=$(...)
v="$v$x"
y=$(...)
v="$v$y"
z=$(...)
v="$v$z"
这会更有意义,特别是如果你使用的每个 $ x的
, $ Y
和 $ Z而言
之后,和/或使用的中间值 $ v
(也许在命令重新三重点psented $ p $) 。用于将与任何的Bourne shell衍生而来的工作串联符号;替代 + =
shell会用更少的贝壳工作,但可能会更有效(与强调略)。
This would make more sense, especially if you use each of $x
, $y
and $z
later, and/or use intermediate values of $v
(perhaps in the commands represented by triple dots). The concatenation notation used will work with any Bourne-shell derivative; the alternative +=
shell will work with fewer shells, but is probably slightly more efficient (with the emphasis on 'slightly').
这篇关于击变串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!