在 Bash 中连接变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14325722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:11:36  来源:igfitidea点击:

Concatenating variables in Bash

bashshellstring-concatenation

提问by Dan Hall

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:

毫无疑问,愚蠢的问题,我正在尝试在变量中间添加一个变量,因此例如在 PHP 中,我会这样做:

$mystring = $arg1 . '12' . $arg2 . 'endoffile';

so the output might be 20121201endoffile, how can I achieve the same in a linux bash script?

所以输出可能是20121201endoffile,我怎样才能在 linux bash 脚本中实现相同的目标?

回答by Gilles Quenot

Try doing this, there's no special character to concatenate in bash :

尝试这样做,在 bash 中没有要连接的特殊字符:

mystring="${arg1}12${arg2}endoffile"

explanations

解释

If you don't put brackets, you will ask bashto concatenate $arg112 + $argendoffile(I guess that's not what you asked) like in the following example :

如果你不加括号,你会要求bash连接$arg112 + $argendoffile(我想这不是你问的),如下例所示:

mystring="$arg112$arg2endoffile"

The brackets are delimitersfor the variables when needed. When not needed, you can use it or not.

括号是需要时变量的分隔符。当不需要时,您可以使用或不使用它。

another solution

另一种解决方案

(不太便携:需要bashbash> 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

http://mywiki.wooledge.org/BashFAQ/013