iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐚

Implementing zsh-style Automatic Newlines in Bash

に公開
2021/07/15

When using bash and running an echo without a newline,

some people might find it unpleasant to see it displayed like this. In the case of zsh, when you run an echo without a newline like this, a % is displayed as follows, and the prompt is correctly shown at the beginning of the line.

I wanted to achieve this in bash too, and upon searching, I found the following Stack Overflow article.

https://serverfault.com/questions/97503/bash-how-to-know-if-the-last-commands-output-ends-with-a-newline-or-not/97543#97543

This PROMPT_SP is a string that is output before the prompt is displayed. In this Stack Overflow answer, it is achieved by displaying a % and then overwriting it with spaces equal to the column width.

However, this method is not ideal for those who use prompt customization hacks like Starship.

In bash, you can use the following method to determine the current column position:

echo -en "\E[6n"
read -sdR CURPOS

Executing this returns the device status of a terminal supporting VT220, and the response is stored in CURPOS via the read command. For Starship users, you can define a function to be called before the prompt is displayed using the starship_precmd_user_func variable. By adding the following to your .bashrc, you can achieve the same behavior as in zsh.

function output_newline(){
  echo -en "\E[6n"
  read -sdR CURPOS
  [ $(echo $CURPOS | cut -d';' -f 2) -gt 1 ] && echo -e "\e[7m%\e[m"
}
starship_precmd_user_func="output_newline"

Update
I received a great alternative from k-takata-san.

function output_newline(){
  IFS='[;' read -s -d R -p $'\033[6n' -a POS
  [ ${POS[2]} -gt 1 ] && echo -e "\e[7m%\e[m"
}
starship_precmd_user_func="output_newline"

Please note that this may cause display issues on terminals that are not VT220-compatible.

Discussion