Table of Contents
We can also use these methods to add a string to the given string as well.
Using $
Operator
Use the $
operator to add character to string in Bash.
1 2 3 4 5 |
str="Hell" str="${str}o" echo $str |
1 2 3 |
Hello |
the${str}
is used to expand the value of the str
variable and then appends the string o
to it, resulting in the string Hello
. The final value of str
is then printed to the terminal using the echo
command, which outputs Hello
.
If you want to add characters between the String, you can use it as following:
1 2 3 4 5 |
ch="e" str="H{ch}llo" echo $str |
1 2 3 |
Hello |
Using +
Operator
Use the +
concatenation operator to add a character to the string in Bash.
1 2 3 4 5 |
str="Hello" str+="o" echo $str |
1 2 3 |
Hello |
In the above code, a variable called str
is declared and initialized to the string Hell
. We then use the +
concatenation operator to add a character o
to the end of str
. Finally, we use the echo
command to print the value of str
, which is Hello
.
Using printf
Command
Use the printf
command to add a character to the string in Bash
1 2 3 4 5 |
str="Hell" printf -v str '%so' "$str" echo $str |
1 2 3 |
Hello |
In the above code, the printf -v str '%so' "$str"
uses the printf
command to format a string and assign it to the variable str
. The -v
option tells printf
to assign the formatted string to the variable specified after it. The format string '%so'
specifies that the value of $str
should be inserted at the position of %s
, followed by the string o
. The resulting string is then assigned to str
.
Add Character to String at beginning
If you want to add character at beginning, you can easily do it using ${}
syntax.
1 2 3 4 5 |
ch="H" str="{ch}ello" echo $str |
1 2 3 |
Hello |
Further reading:
Add Character to String at the end
If you want to add character at end, you can easily do it using ${}
syntax.
1 2 3 4 5 |
ch="H" str="Hell{ch}" echo $str |
1 2 3 |
Hello |
Considering the above solutions, the concatenation
operator, $ operator
, and printf
methods can add a character to the string. You can choose any of them depending on your use case.
That’s all about bash add character to String.