shell script to concatenate strings

Shell Script to Concatenate Strings

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

2. Add shell script

Add the following shell script for string concatenation.



for f in "$@"

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

4. Test shell script

You may test the shell script by passing strings as command line arguments separated by space.

$ sudo ./ Hello World

$ sudo ./ What A Wonderful World

If you want to add a space between the words, just modify the for loop statement as follows

for f in "$@"
  final_string+=$f+" "

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

Leave a Reply

Your email address will not be published.