A little script to print (repeat) a character or string n number of times

Sometimes, I want to repeatedly echo a single characther in the shell a certain number of times (like 72 dashes to make a line separator, for instance). But actually running echo followed by 72 dash characters is too annoying and I can never remember the proper fprint syntax to just whip it out on demand. So here's a quick script to repeatedly print a character (or a string) an arbitrary number of times.

A lovely line separator, 72 characters wide (print dash 72 times):

ak@loon:~$ repeat - 72
------------------------------------------------------------------------

Characters that have a special meaning for the shell are best quoted (or escaped). To print round quotes 10 times:

ak@loon:~$ repeat "()" 10
()()()()()()()()()()

String example, to echo the obligatory "Hello World!" 5 times:

ak@loon:~$ repeat "hello world! " 5
hello world! hello world! hello world! hello world! hello world!

And here's the script:

#!/bin/bash

c=$1
n=$2

if ! [ "$c" ] || ! [ "$n" ]; then
  echo "Error: please supply a string and the number of times to repeat it, e.g.:"
  echo "$(basename $0) - 5"
else
  printf "%${n}s\n" | sed "s/ /${c}/g"
fi

Leave a comment

NOTE: Enclose quotes in <blockquote></blockquote>. Enclose code in <pre lang="LANG"></pre> (where LANG is one of these).