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?
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?
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.
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
%*s
is a space char and 2nd argument is the character count. what does the last argument ''
mean?
–
Jun 12 '15 at 00:44
%*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
bash
? – Janis Jun 11 '15 at 02:44