0

How to concatenate two strings in a bash script?

Example: I would like to concate "foo" and "bar", but WITHOUT creating a new variable for "bar".

VAR="foo"

echo "$VARbar"

This does not work, because it is considered as variable name VARbar.

3 Answers 3

2

This can work:

echo "${VAR}bar"

if you put brackets " wrapping the name, you can concatenate it as desired. With it, bash understands the name of the variable is just "VAR" and the rest is just text.

Sign up to request clarification or add additional context in comments.

Comments

1

Use {} to distinguish the variable name i.e.

echo "${VAR}bar"

Comments

0
bash_prompt$ l="aaa"
bash_prompt$ m="bbb"
bash_prompt$ n=$l$m
bash_prompt$ echo $n
bash_prompt$ aaabbb
bash_prompt$ n=$l"bbb"
bash_prompt$ echo $n
bash_prompt$ aaabbb

Bash does string concatenation by default

2 Comments

I suggest to delete leading $ that confuse the answer. Also, make sure you are answering the question. The OP wants to echo $VARbar and to output foobar. Your examples are correct but do not answer it.
check WITHOUT creating a new variable for "bar". echo $VARbar is what he thought can be an approach, but not necessarily must be . Sorry for the leading $, i copy pested them (my PS1 is just odd, i agree :P) I'll make the change

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.