Shell scripts make it easy to work with strings and perform useful string transformations. Sometimes you may need to write shell script for string concatenation. In this article, we will look at how to create shell script to concatenate strings. Our script will allow you to join any number of strings, instead of limiting it to a specific number of string inputs. You can modify this example as per your requirement.
Shell Script to Concatenate Strings
Here is an example to concatenate strings in a shell script.
1. Create empty shell script
Open terminal and run the following command to create an empty script.
$ sudo vi string_concat.sh
2. Add shell script
Add the following shell script for string concatenation.
#!/bin/bash final_string="" for f in "$@" do final_string+=$f done echo $final_string
Save and quit the file. In the above script, we accept the strings to be concatenated as command line arguments. We run a for loop through the list of arguments, and concatenate them one by one to our final string. Lastly, we echo the concatenated string.
3. Make shell script executable
Run the following command to make our script executable.
$ sudo chmod +x string_concat.sh
4. Test shell script
You may test the shell script by passing strings as command line arguments separated by space.
$ sudo ./string_concat.sh Hello World HelloWorld $ sudo ./string_concat.sh What A Wonderful World WhatAWonderfulWorld
If you want to add a space between the words, just modify the for loop statement as follows
for f in "$@" do final_string+=$f+" " done
In this article, we have learnt how to create shell script to concatenate strings. Our script is flexible enough to concatenate any number of strings. We have also seen how to modify the script to add space between any two words during concatenation. You may modify and use it as per your requirement.
Also read:
How to Run Shell Script As Background Process
How to Create Empty Disk Image in Linux
How to Unrar Files with Password in Linux
How to Extract Multipart RAR Files in Linux
How to Find Recently Modified Files in Linux
Related posts:
![](https://fedingo.com/wp-content/uploads/2024/05/db908c05ad732bd197c1eaad1c6675d2.jpeg)
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.