54

I am 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';

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

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Dan Hall
  • 1,474
  • 2
  • 18
  • 43
  • Have you read [bash-script-variable-inside-variable](http://stackoverflow.com/questions/2634590/bash-script-variable-inside-variable) ? – cyberhicham Jan 14 '13 at 20:03

1 Answers1

95

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

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

explanations

If you don't put brackets, you will ask 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.

another solution

(less portable : require bash > 3.1)
$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

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

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223