How Do I Concatenate Strings in a Bash Script?

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

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

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.