This article explores five common ways to combine strings in your Bash scripts and programs. Keep reading to learn more about concatenating strings in Bash and which method is best for your specific situation.

Concatenate Strings

The simplest way to combine strings in Bash is to use the double-quote (“ ”) character. You can enclose your strings within double quotes and combine them to form a single string. This is useful for combining short strings that don’t require any special formatting. The example below demonstrates how to combine two short strings to form a single, long string using double quotes.

The echo command will print the result string.

Concatenate String Variable with Literal

A literal represents a fixed value. Instead of joining two string variables, we can also join a literal string with a variable value. For example, take an input of a user’s first name and prefix it with a “Welcome” literal string.

Execute the above script, It will prompt you to enter your Name. Then concatenate “Welcome” as a prefix to the input string and print the results.

Concatenate Strings with += Operator

In general programming language the += adds the RHS value to LHS. You can also use this method to Concatenate the RHS string variable to the LHS string.

This will print: Welcome to TecAdmin

Using the Printf Command

In bash, print is a command that is used to format and print data to standard output. The -v option initialize a variable with the output rather than print on output.

This will print: Hello Mr. Rahul

Using loop

When there is an undefined number of the input strings, you need to concatenate them into a single string. The while loop will help you with the join (+=) operator. For example, you need to read all lines of a file and concatenate them in a single string. To do this, we will read the file content line by line and concatenate them.

Conclusion

This article explores five common ways to combine strings in your Bash scripts and programs. The simplest way to combine strings is to use the double-quote character. You can also use the for loop command to iterate through a series of words and combine them into a single string. The join (+) command is a Bash built-in that can be used to combine a series of items into a single string. The BASH scripting language allows you to perform more complex string operations including combining variables, calculations, and more.