I have the following code which displays a message based on whether or not the last command was executed successfully (which is prepended to PS1):
function previous_command() {
exit_code=$?
if [ $exit_code -eq 0 ]; then
echo -e "\033[1;4;32mCommand successful\033[00m"
else
echo -e "\033[1;4;31mCommand failed with exit code $exit_code\033[00m"
fi
}
What I want to do is have the underline extend all the way to the edge of the current terminal window, like this:

Assuming the exit code is one character long, I can hard-code it to 80 characters by just adding spaces, but this fails if I resize the window or get an exit code of 10 or greater.
How can I make this function dynamically continue the line to the edge of the terminal window?
You can left align a string with spaces to 42 characters with printf "%-42s". You can get the window width with $COLUMNS. Putting them together, we get:
printf "\033[1;4;31m%-${COLUMNS}s\033[00m" "Command failed with $RANDOM"
No matter how many digits the (here random) number is, the line always extends all the way to the edge.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With