How do I concatenate strings in a bash script?

21

3

How can I concatenate strings and variables in a shell script?

stringOne = "foo"

stringTwo = "anythingButBar"

stringThree = "? and ?"

I want to output "foo and anythingButBar"

Moshe

Posted 2011-01-27T22:19:04.333

Reputation: 5 474

Answers

29

Nothing special, you just need to add them to your declaration.

for example:

[Zypher@host01 monitor]$ stringOne="foo"
[Zypher@host01 monitor]$ stringTwo="anythingButBar"
[Zypher@host01 monitor]$ stringThree=$stringOne$stringTwo
[Zypher@host01 monitor]$ echo $stringThree 
fooanythingButBar

if you want the literal word 'and' between them:

[Zypher@host01 monitor]$ stringOne="foo"
[Zypher@host01 monitor]$ stringTwo="anythingButBar"
[Zypher@host01 monitor]$ stringThree="$stringOne and $stringTwo"
[Zypher@host01 monitor]$ echo $stringThree 
foo and anythingButBar

Zypher

Posted 2011-01-27T22:19:04.333

Reputation: 2 077

You can also do stringThree=$stringOne" and "$stringTwo. – Armfoot – 2015-12-04T11:38:41.173

4If I might make a suggestion, your prompt is noisy and obscures your answer (and a space after the dollar sign would help readability). Something like $ stringOne="foo", for example. Also, the prompt shouldn't appear on an output line (the lines after the echos). Otherwise +1. – Paused until further notice. – 2011-01-27T22:31:55.313

10echo ${stringOne}and${stringTwo} if you don't want spaces – max taldykin – 2011-01-28T09:41:16.927

5

If instead you had:

stringOne="foo"
stringTwo="anythingButBar"
stringThree="%s and %s"

you could do:

$ printf "$stringThree\n" "$stringOne" "$stringTwo"
foo and anythingButBar

Mikel

Posted 2011-01-27T22:19:04.333

Reputation: 7 890