Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

stringOne = "foo"

stringTwo = "anythingButBar"

stringThree = "? and ?"

I want to output "foo and anythingButBar"

share|improve this question
add comment

2 Answers 2

up vote 20 down vote accepted

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
share|improve this answer
    
I changed the question slightly. –  Moshe Jan 27 '11 at 22:27
    
@Moshe changed the answer slightly :) –  Zypher Jan 27 '11 at 22:29
4  
If 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. –  Dennis Williamson Jan 27 '11 at 22:31
5  
echo ${stringOne}and${stringTwo} if you don't want spaces –  max taldykin Jan 28 '11 at 9:41
add comment

If instead you had:

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

you could do:

$ printf "$stringThree\n" "$stringOne" "$stringTwo"
foo and anythingButBar
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.