21

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

stringOne = "foo"

stringTwo = "anythingButBar"

stringThree = "? and ?"

I want to output "foo and anythingButBar"

30

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

stringOne="foo"
stringTwo="anythingButBar"
stringThree=$stringOne$stringTwo
echo $stringThree 

fooanythingButBar

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

stringOne="foo"
stringTwo="anythingButBar"
stringThree="$stringOne and $stringTwo"
echo $stringThree 

foo and anythingButBar

3
  • 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
  • 11
    echo ${stringOne}and${stringTwo} if you don't want spaces – max taldykin Jan 28 '11 at 9:41
  • You can also do stringThree=$stringOne" and "$stringTwo. – Armfoot Dec 4 '15 at 11:38
6

If instead you had:

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

you could do:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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