| Keywords: | print,line |
|---|---|
| Contributor: | TheBonsai, prince_jammys, ccsalvesen and others |
The purpose of this small code collection is to show some code that draws a horizontal line using as less external tools as possible (it's not a big deal to do it with AWK or Perl, but with pure or nearly-pure Bash it gets more interesting).
In general, you should be able to use this code to repeat any character or character sequence.
Not a miracle, just to be complete here.
# of course you can use echo(1), too printf -- '--------------------\n'
This one simply loops 20 times, always draws a dash, finally a newline
for ((x = 0; x < 20; x++)); do printf -- '-' done printf '\n'
This one uses the printf command to print an empty field with a minimum field width of 20 characters. The text is padded with spaces, since there is no text, you get 20 spaces. The spaces are then converted to - by the tr command.
printf '%20s\n' | tr ' ' '-'
whitout an external command, using a bash specific expansion:
printf -v res '%20s'
printf "%s\n" "${res// /-}"
This one is a variant of the one above. It uses tput cols to find the width of the terminal and set that number as the minimum field witdh.
printf "%$(tput cols)s\n"|tr ' ' '='
This one is a bit tricky. The format for the printf command is %.0s, which specified a filed with the maximum length of zero. After this field, printf is told to print a dash. You might remember that it's the nature of printf to repeat, if the number of format specifications is less than the number of given arguments. With brace expansion {1..20}, 20 arguments are given (you could easily write 1 2 3 4 ... 20, of course!). Following happens: The zero-length field plus the dash is repeated 20 times. A zero length field is, naturally, invisible. What you see is the dash, repeated 20 times.
# Note: you might see that as %.s, which is a (less documented) shorthand for %.0s
printf '%.0s-' {1..20}
printf '\n'
if the 20 is variable, you can use eval (take care that using eval is potentially dangerous if you evaluate external data):
eval printf '%.0s-' {1..$(tput cols)}
Preparing enough dash in advance, we can then use a (bash specific) expansion:
hr=---------------------------------------------------------------\
----------------------------------------------------------------
echo ${hr:0:$(tput cols)}
Discussion