Languages
[Edit]
EN

Bash - repeat a character N times

3 points
Created by:
Amir-Hashempur
547

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:

++++++++++
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Bash

Bash - repeat a character N times
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join