0

Is there any way to preserve partial line in bash like zsh? My bash prompt messes up without newline and for printing other non-printable escape characters.

Thanks in advance!

I've tried PS1="\[\e[0m\]\n$PS1". But I think that's not a perfect solution. I just want to set my bash prompt to add newline if no EOL detected in previous output.

  • Questions about interactive shell configuration are better fit for [unix.se] – Charles Duffy Oct 26 '22 at 20:08
  • In general, though, what you want to do is to use `tput` to ask the terminal where the cursor is. (The shell doesn't read the output of programs it runs -- that output is written direct to the TTY -- so without doing that query it can't tell if the program ended with a newline or not). – Charles Duffy Oct 26 '22 at 20:08
  • [How to get the cursor position in bash](https://stackoverflow.com/questions/2575037/how-to-get-the-cursor-position-in-bash) discusses the necessary elements. Also, on [unix.se], [get vertical cursor position](https://unix.stackexchange.com/questions/88296/get-vertical-cursor-position) – Charles Duffy Oct 26 '22 at 20:11
  • 2
    (...realizing that I left out a piece: `PROMPT_COMMAND` is how one specifies a function to run before the prompt is printed; that function can use the techniques in the answers linked above to assign an appropriate PS1) – Charles Duffy Oct 26 '22 at 20:25
  • @CharlesDuffy Yes, the "discovery" of `PROMPT_COMMAND` was a real happening for me. A special prompt for every type of directory I'm in. `git`, `clearcase`, ... `/dev`, `/etc` - the customization can just go on and on. At some time when we migrated from `clearcase` to `git` I had a prompt combining the info I needed to not make mistakes :.) – Ted Lyngmo Oct 28 '22 at 19:53

1 Answers1

1

##~/.local/bin/add_newline

#!/usr/bin/bash

printf "\E[6n";read -sdR CURPOS; CURPOS=${CURPOS#*[}; C="${CURPOS#*;}"

[ "$C" -ne 1 ] && echo

$ chmod +x ~/.local/bin/*

##~/.bashrc

PROMPT_COMMAND="${PROMPT_COMMAND}${PROMPT_COMMAND:+;} add_newline"

Thanks @CharlesDuffy

  • 1
    BTW, I generally suggest `printf %b ...` instead of `echo -n ...`; the [POSIX specification for `echo`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html) makes that same recommendation (see APPLICATION USAGE and RATIONALE sections in particular). And it'd be a bit better performance-wise to define a function instead of using an external executable. – Charles Duffy Dec 29 '22 at 19:55