EN
Bash - repeat a character N times
3
points
This article will show you how to repeat a character N times in Bash.
To repeat character it is necessary to write some loop.
Quick solution (+
repeated 10
times):
#!/bin/bash
for i in {1..10}; do echo -n "+"; done
or:
#!/bin/bash
for (( i = 0; i < 10; ++i )); do echo -n "+"; done
Note: the
-n
attribute prevents every character from being displayed on a newline.
Reusable function
In this case, we use a predefined function that repeats character.
#!/bin/bash
function repeat_character()
{
local count="$1"
local character="$2"
for (( i = 0; i < "$count"; ++i ))
do
echo -n "$character"
done
}
# Usage example:
repeat_character 10 "+"
repeat_character 10 "^"
Output:
++++++++++
^^^^^^^^^^
Another solutions
In this section, we use a text variable that collects repeated characters.
1. Bash for
loop syntax
#!/bin/bash
character="+"
text=""
for i in {1..10}
do
text="${text}${character}"
done
echo "$text"
Output:
++++++++++
2. C for
loop syntax
#!/bin/bash
count=10
character="+"
text=""
for (( i = 0; i < "$count"; ++i ))
do
text="${text}${character}"
done
echo "$text"
Output:
++++++++++