help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Where is the usage of '.' in printf documented?


From: Greg Wooledge
Subject: Re: [Help-bash] Where is the usage of '.' in printf documented?
Date: Fri, 20 Mar 2015 08:15:09 -0400
User-agent: Mutt/1.4.2.3i

On Thu, Mar 19, 2015 at 03:56:43PM -0500, Peng Yu wrote:
> printf "%0.s-" {1..10}

I hate ugly hacks like this.  Truly, I do.

What that bit of code says, in human-readable form, is "For every argument
after the format, I want you to print the argument truncated to length
zero, and then a hyphen."  Or in simpler terms, "print this many hyphens
in a row in a really twisted way".

For some reason, the code you found has replaced the slightly more
readable %0.0s with %0.s (and you could also use %.s for the same result,
dropping both zeroes).  I'd at least stick with %0.0s because I find
that the least unclear of the various forms.

Some time ago on the IRC channel, we did timing experiments on various
ways to implement "print an arbitrary number of X's in a row" in bash.
My version won for speed, but it has an obvious limitation:

nXs() {
  local Xs="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
  echo "${Xs:0:$1}"
}

For readability and limitation-removal over speed, I would prefer
this one:

nXs() {
  local i
  for ((i=0; i<$1; i++)); do
    printf 'X'
  done
  echo
}

There are many other variants (passing the character to be repeated as
an additional argument, suppressing the final newline, ...) and many
other ways to write it.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]