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?
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.
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".
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.
Try doing this, there's no special character to concatenate in bash :
mystring="${arg1}12${arg2}endoffile"
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) $ arg1=foo $ arg2=bar $ mystring="$arg1" $ mystring+="12" $ mystring+="$arg2" $ mystring+="endoffile" $ echo "$mystring" foo12barendoffile
See http://mywiki.wooledge.org/BashFAQ/013
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With