Bash – Add Newline to Prompt if Too Long

bashpromptterminalzsh

I show my full working directory plus other information (git, etc) in my bash prompt and sometimes it gets very long.

I want to add a newline to the end of my prompt so I can type the command on the next line, but only if the prompt is long e.g. more than 50 characters.

| ~ $ Typing a command here is nice                                              |
| ~/foo/longDirectoryName/longsubirectory/src/package (master +*) $ Typing here s|
| ucks. I want to just start on a new line                                       |

Obviously, If I wanted to always type my command on the next line, I could just add a newline to PS1 (as in this post). But I haven't found a way to do that conditionally because PS1 is just a format string.


P.S. I'm actually using ZSH trying to customize the Agnoster theme but I imagine any solution for bash in general would help.

Best Answer

In zsh, that's what the %<number>(l:<yes>:<no>) prompt expansion is for. When the number is negative, like -30, if there are at least 30 characters left until the right edge of the screen, then the yes text is output, otherwise no, so:

PS1=$'%~%-30(l::\n)$ '

Would insert a newline if fewer than 28 characters (30 minus the "$ ") are left for you to use on the line.

You can do your 50 or more with:

PS1=$'%~%50(l:\n:)$ '

But IMO, it's more useful to guarantee a minimum available space, than a maximum unusable space.

See the manual for details. You'll find other directives to truncate long prompts and replace with ellipsis for instance which you may also find useful.

Note that zsh prompt expansion is completely different from that of bash. It's actually closer to that of tcsh, so solutions for bash are unlikely to be of much use for zsh, though it's generally more true the other way round.

Related Question