Article pages now have a discussion option at the bottom (moderated/captcha, but no registration needed)

Print a horizontal line

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.

The simple way: Just print it

Not a miracle, just to be complete here.

# of course you can use echo(1), too
printf -- '--------------------\n'

The iterative way

This one simply loops 20 times, always draws a dash, finally a newline

for ((x = 0; x < 20; x++)); do
  printf -- '-'
done
printf '\n'

The simple printf way

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// /-}"

A line across the entire width of the terminal

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 ' ' '='

The more advanced printf way

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)}

The parameter expansion way

Preparing enough dash in advance, we can then use a (bash specific) expansion:

hr=---------------------------------------------------------------\
----------------------------------------------------------------
echo ${hr:0:$(tput cols)}

Related articles

Discussion

Enter your comment
 
snipplets/print_horizontal_line.txt · Last modified: 2010/03/21 15:30 by thebonsai
GNU Free Documentation License 1.2
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0