Print a character repeatedly in bash [duplicate]

There’s actually a one-liner that can do this:

    printf "%0.s-" {1..10}

prints

    ----------

Here’s the breakdown of the arguments passed to printf:

  • %s – This specifies a string of any length
  • %0s – This specifies a string of zero length, but if the argument is longer it will print the whole thing
  • %0.s – This is the same as above, but the period tells printf to truncate the string if it’s longer than the specified length, which is zero
  • {1..10} – This is a brace expansion that actually passes the arguments “1 2 3 4 5 6 7 8 9 10”
  • “-” – This is an extra character provided to printf, it could be anything (for a “%” you must escape it with another “%” first, i.e. “%%”)
  • Lastly, The default behavior for printf if you give it more arguments than there are specified in the format string is to loop back to the beginning of the format string and run it again.

The end result of what’s going on here then is that you’re telling printf that you want it to print a zero-length string with no extra characters if the string provided is longer than zero. Then after this zero-length string print a “-” (or any other set of characters). Then you provide it 10 arguments, so it prints 10 zero-length strings following each with a “-“.

It’s a one-liner that prints any number of repeating characters!

Edit:

Coincidentally, if you want to print $variable characters you just have to change the argument slightly to use seq rather than brace expansion as follows:

    printf '%0.s-' $(seq 1 $variable)

This will instead pass arguments “1 2 3 4 … $variable” to printf, printing precisely $variable instances of “-“

Leave a Comment