Languages
[Edit]
EN

Bash - repeat a character N times

3 points
Created by:
Amir-Hashempur
337

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

character="+"

for i in {1..10}
do 
	echo -n "$character"
done

# Where:
#   10 means the number of repeats and should be replaced desired value

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 solution

In this case, we use a text variable that collects repeated characters.

#!/bin/bash

count=10
character="+"

text=""

for (( i = 0; i < "$count"; ++i ))
do 
	text="${text}${character}"
done

echo "$text"

Output:

++++++++++

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