1
print '*' * 80

This python snippet prints 80 asterisks, which I use often as delimiters in log files.

How can I do it in bash script using operator overloading?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

3

In shell (ksh, zsh, bash) you can do:

stars=$(printf '%*s' 80 '')
echo "${stars// /*}"

With bash there's the option of doing:

printf -v stars '%*s' 80 ''
echo "${stars// /*}"

Explanation: The printf uses a format string %*s which means to produce a string of a length that is provided through an argument. So the first argument (80) specifies the length and the second argument specifies the string ('', an empty string) to be effectively printed, but blank-padded to the defined width. Note that this could also be expressed as printf "%80s" '', though I used the parameterized version for the length to make it explicit that it can be a variable parameter.

Janis
  • 14,222
  • printf -v will help avoid the need for a command substitution – iruvar Jun 11 '15 at 02:45
  • For bash that's correct. - But note that printf -v is not widely available in shells thus less portable. In ksh, e.g., you don't have it, and in ksh you also don't have a reason to avoid this command substitution (no subshell process in this case). - So despite the OP's question restricted itself by its formulation to bash users of other shells may prefer a wider support of that code pattern. – Janis Jun 11 '15 at 02:50
  • hi janis, i understand for printf, %*s is a space char and 2nd argument is the character count. what does the last argument '' mean? –  Jun 12 '15 at 00:44
  • 1
    @Madhavan Kumar; %*s is the format string, 80 and '' are the arguments for printf; I added an explanation in my answer. – Janis Jun 12 '15 at 03:02