44

How to concat variable and string in bash script ?

val1 = Variable1 + "any string "

eg :

val1 = $i + "-i-*"

where i = 24thMarch

I want echo val1 :

24thMarch-i-*

What is proper proper to get the solution ?

2
  • val1="$i-i-*" should work. Regarding your first question: val1="${Variable1}any string" (note the curlies). Commented Sep 21, 2015 at 13:47
  • uuups, just saw that @gniourf already had the same idea as me in my answer. Commented May 4, 2018 at 6:27

3 Answers 3

74

Strings can be concatenated by simply creating a new string and expanding the values of the previous string variables directly within it.

value="${variable} let's expand some more vars ${other_variable}"

You must always wrap variable expansions in double quotes, otherwise your string will end at the first encountered whitespace character in the variables, which is a very common mistake.

Note that there should be no spaces around the = in an assignment.

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

1 Comment

I didn't mention anything about single quotes. In the second example, the curly braces are needed to separate the variable names with literal text. Granted, the curly braces around the second variable are not needed since the is no ambiguity. The double quotes in the second example are superfluous because there are no spaces but they don't do any harm.
3

Nice.

Mac OS X 10.12 works with following ...


#!/bin/bash

var1=bar
var2=foo
var3="$var1"sometext
echo $var3

Result

barsometext

3 Comments

Where does the value from var2 ("foo") in the result come from?
Result should be modify. Actual result is barsometext
No, var2 has no impact to the result (var3) that is outputted and can hereby removed from your answer.
1

Late for the party, my 2 cents for another solu., also works in zsh:

i=`date +%d%b`

val1="$i-i-*"

3 Comments

@LogicalBranch I rolled back your edit; it introduced errors.
@PeterPanX Ditto; your "typo fixes" broke perfectly good, valid code.
@tripleee Ah! Hadn't realised, thanks for the heads up.

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.