How do I concatenate strings in a bash script?

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

stringOne = "foo"

stringTwo = "anythingButBar"

stringThree = "? and ?"

I want to output "foo and anythingButBar"

2 Answers

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

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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like