Bash的变量串联 [英] Bash variables concatenation
问题描述
愚蠢的问题毫无疑问,我想添加一个变量变量的中间,所以例如在PHP中我会做到这一点:
stupid question no doubt, I'm trying to add a variable to the middle of a variable, so for instance in PHP i would do this:
$mystring = $arg1 . '12' . $arg2 . 'endoffile';
所以输出可能是 20121201endoffile
,我怎么能达到同样的在Linux bash脚本?
so the output might be 20121201endoffile
, how can I achieve the same in a linux bash script?
推荐答案
尝试这样做,有没有特殊字符在bash来连接:
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
说明
如果你不把括号,你会问庆典来连接 $ arg112 + $ argendoffile
(我想这是不是你问什么)就像下面的例子:
explanations
If you don't put brackets, you will ask bash to concatenate $arg112 + $argendoffile
(I guess that's not what you asked) like in the following example :
mystring="$arg112$arg2endoffile"
需要时的
括号的分隔符的的变量。在不需要的时候,你可以用它或没有。
The brackets are delimiters for the variables when needed. When not needed, you can use it or not.
另一种解决方案
(不便于携带:要求庆典
> 3.1)
another solution
(less portable : requirebash
> 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile
请参阅 http://mywiki.wooledge.org/BashFAQ/013
这篇关于Bash的变量串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!