Linux Tips: How to Concatenate Strings in Bash

Updated

bash concatenate strings

Concatenate strings in bash by writing the pieces next to each other (target=$prefix$suffix) and append to an existing variable with str+=" World". Quote every expansion of the result ("$target", not $target), or word splitting and glob expansion will break it apart. Single quotes keep everything inside literal; double quotes still expand $variables.

Don’t write var="Hello, "world" to combine fixed text and a variable. The quotes are unbalanced: paste it as a line in a script and bash doesn’t finish parsing it:

$ cat script.sh
#!/bin/bash
var="Hello, "world"
$ bash script.sh
script.sh: line 2: unexpected EOF while looking for matching `"'
script.sh: line 3: syntax error: unexpected end of file

Reading it left to right: "Hello, " is a complete, closed double-quoted string. Then world is a bare, unquoted word; it gets concatenated onto the string literally, contributing the five characters world. Then the final " opens a new quoted string that is never closed, so bash keeps scanning past the end of the line, past the end of the file, and gives up (how to write a bash script covers the loop-syntax errors that come up right after concatenation, such as a missing separator before done).

If the goal was a string containing a literal double quote (Hello, "world") there are two ways to write it that actually parse:

var='Hello, "world"'          # single quotes: everything inside is literal
echo "$var"                    # Hello, "world"

var="Hello, \"world\""        # double quotes: escape the inner quotes
echo "$var"                    # Hello, "world"

Single quotes suppress all expansion, including $variables and escapes (the bash manual’s quoting section puts it as preserving the literal value of each character within the quotes), so use them when nothing inside needs to expand. Double quotes still expand $variables and command substitutions, so an embedded literal quote has to be escaped with a backslash.

Appending with +=

For building a string incrementally, += is clearer than repeating the variable name on both sides (appending output to a file rather than a variable is covered in append strings to a file in bash):

str="Hello"
str+=" World"
echo "$str"      # Hello World

Why "${var}" matters when you concatenate

An unquoted expansion goes through word splitting and glob expansion before it reaches whatever you’re concatenating into. Two demonstrations, both run against real files:

$ name="file one.txt"
$ echo unquoted: $name
unquoted: file one.txt
$ echo quoted:   "$name"
quoted:   file one.txt

That one looks harmless printed by itself, but pass the unquoted form as a single argument to a command that cares about argument count (a path check, a comparison, an array assignment) and it silently becomes two arguments: file and one.txt. The trap gets worse when the variable’s value contains a glob character:

$ touch "file one.txt" "file two.txt"
$ pattern="file*.txt"
$ echo unquoted: $pattern
unquoted: file one.txt file two.txt
$ echo quoted:   "$pattern"
quoted:   file*.txt

Unquoted, $pattern isn’t concatenated as the nine characters file*.txt: it’s expanded against the filesystem first, and every matching file lands in the result. This is exactly what happens when you concatenate a path prefix and a filename-with-spaces without quotes:

$ prefix="/tmp/backup-"
$ suffix="file one.txt"
$ target=$prefix$suffix
$ set -- $target; echo "arg count: $#"
arg count: 2

$target holds the single string /tmp/backup-file one.txt, which is correct, but handing it to a command unquoted splits it into /tmp/backup-file and one.txt at the space. Quote every expansion of a concatenated variable: "$target", not $target. The unbalanced-quote failure, both quoting fixes, +=, the word-splitting and glob cases and the ${price} example all run through your own bash in bash-concatenate-strings.sh, with no network access or root.

A literal $ in the result

Inside double quotes, $ triggers expansion when followed by a name, a digit, a special-parameter character such as ? or #, (, or {. A nonzero digit after the $ makes it a positional parameter, so echo "Price: $5.00" prints Price: .00, because $5 is the fifth argument and there is none. To keep a literal $5 in the result, put it in a single-quoted variable and expand that with braces, as here:

$ price='$5'
$ msg="Price: ${price}.00"
$ echo "$msg"
Price: $5.00

Using ${price} rather than bare $price also avoids a real ambiguity here: $price.00 would still work (. isn’t a valid identifier character, so bash stops the name there), but if the next character could plausibly extend a variable name, the braces are what stop bash from reading too far.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.