Reputation: 33920
I need a command that will draw a horizontal "line" in the terminal. The line must be exactly the width of the terminal long (regardless of a current terminal width) and consist of a dash character (although a unicode symbol for a horizontal line can be also used).
It is better if it can be colored.
I need to use it like this:
echo some text
drawline
echo more text
And the output would look something like this:
echo some text
---------------------------------------------------------------------------------
echo more text
Upvotes: 34
Views: 29447
Reputation: 10944
I'll add some details to the current top answer. You can use the following "hack" (also as suggested here):
printf '%.s─' $(seq 1 $(tput cols))
Notice how this doesn't use the simple dash -
but instead the box drawing dash ─
. This way consecutive dashes actually connects which prints a nice continuous line:
This nice line ────────────────────────────
And not this one ----------------------------
You can for example use this to show a line before (and/or after) every command registering hooks using zsh
# ~/.zshrc
draw_hline=false
preexec() {
if [[ $1 == ls* ]]; then
hline
draw_hline=true
fi
}
precmd() {
if [ $draw_hline = true ]; then
hline
echo
fi
draw_hline=false
}
Registering hooks using bash can probably be done in a very similar way using this.
Upvotes: 21
Reputation: 322
you can use tput
to set colors and printf
to print line according to number of columns.
export RED=$(tput setaf 1 :-"" 2>/dev/null)
export GREEN=$(tput setaf 2 :-"" 2>/dev/null)
export YELLOW=$(tput setaf 3 :-"" 2>/dev/null)
export BLUE=$(tput setaf 4 :-"" 2>/dev/null)
export RESET=$(tput sgr0 :-"" 2>/dev/null)
echo $GREEN some text $RESET
echo $RED; printf -- "-%.0s" $(seq $(tput cols)); echo $RESET
echo $YELLOW more text $RESET
Upvotes: 3
Reputation: 1509
Super simple horizontal ruler:
repeat $(tput cols) echo -ne "-";
Upvotes: -1
Reputation: 23864
A simple Perl one-liner
stty size | perl -ale 'print "-"x$F[1]'
NOTE
you can see the height and width of your terminal with stty size
Upvotes: 4
Reputation: 8613
In bash and zsh there is the $COLUMNS
variable which you can use.
I use this line for that purpose:
printf %"$COLUMNS"s |tr " " "-"
You can also use seq
, but this is not as intuitive as the other solution:
seq -s- $COLUMNS|tr -d '[:digit:]'
Edit:
It seems that $COLUMNS
is a local bash variable and you will need to export it. So now there are (at least) 2 options.
Export the variable before you call the script:
export COLUMNS; ./your_script.sh
Use tput
as Zumo de Vidrio suggests.
printf %"$(tput cols)"s |tr " " "-"
Upvotes: 23
Reputation: 2091
Try with:
echo some text
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
echo some text
Upvotes: 35