Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating variables in Bash [duplicate]

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

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

like image 893
Dan Hall Avatar asked Jan 14 '13 20:01

Dan Hall


People also ask

How do I combine two variables in bash?

The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.

How do I append a string to a variable in bash?

As of Bash version 3.1, a second method can be used to concatenate strings by using the += operator. The operator is generally used to append numbers and strings, and other variables to an existing variable. In this method, the += is essentially shorthand for saying "add this to my existing variable".

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


1 Answers

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 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.

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

like image 87
Gilles Quenot Avatar answered Sep 25 '22 12:09

Gilles Quenot