Draw a Line Between Bash Commands

Patrick DeYoreo
2 min readAug 5, 2019

--

Sick of scrolling through the terminal, searching for the end of output and the start of the next prompt? Well I’ve got a solution for you. Why not separate your commands with a stylish line?

First, let’s make a function to draw a line across the terminal. We can get the terminal width using the COLUMNS variable. Here’s what the bash man page has to say about COLUMNS:

Used by the select compound command to determine the terminal width when printing selection lists. Automatically set if the checkwinsize option is enabled or in an interactive shell upon receipt of a SIGWINCH.

So if we want COLUMNS to expand to the correct value, we can simply enable the checkwinsize option. To do this, we use the command:

shopt -s checkwinsize

We’ll use the “Box Drawings Light Horizontal” Unicode character (i.e. ). This can be printed using the command:

printf '\u2500'

Now let’s create the function draw_line:

draw_line()
{
local COLUMNS="$COLUMNS"
while ((COLUMNS-- > 0)); do
printf '\u2500'
done
}

(NOTE: we create the local variable COLUMNS to avoid changing the global value)

To execute this as part of our prompt, we need to set the variable PS1. Here’s what the bash man page has to say about PS1:

The value of this parameter is expanded (see PROMPTING below) and used as the primary prompt string.

What if we simply set PS1 to draw_line? Then the string draw_line will undergo expansion and our prompt will be the literal text draw_line. Instead, we want our function to execute, so we put it inside a command substitution. We want the command substitution to be expanded at every prompt (in case the terminal width changes), so we wrap it in single quotes. Lastly, we don’t want to overwrite the existing prompt, so we append a newline followed by the current value of PS1. We end up with the following statement:

PS1='$(draw_line)\n'$PS1

In order to make these changes persist beyond the current shell, these commands must be added to your bash startup script. Open up the file ~/.bashrc in your favorite editor and add the following lines:

shopt -s checkwinsizedraw_line()
{
local COLUMNS="$COLUMNS"
while ((COLUMNS-- > 0)); do
printf '\u2500'
done
}
PS1='$(draw_line)\n'$PS1

Now start a shell and enjoy! Thanks for reading.

--

--

Patrick DeYoreo
Patrick DeYoreo

No responses yet