在Bash中串联变量 [英] Concatenating variables in Bash

查看:52
本文介绍了在Bash中串联变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

毫无疑问,这是愚蠢的问题,我正在尝试将变量添加到变量的中间,因此例如在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.

另一种解决方案

(便携式性较差:需要 bash > 3.1)

another solution

(less portable : require bash > 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆