Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bahamas10
Last active December 23, 2015 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bahamas10/6567725 to your computer and use it in GitHub Desktop.
Save bahamas10/6567725 to your computer and use it in GitHub Desktop.
zsh style trailing newline in bash

Trailing Newlines

In zsh, if a command lacks a trailing newline (like echo -n hello), an inverted percent sign with a newline is appended to the output so the prompt can be printed on its own line, not directly after the output. The bashrc in this example will emulate this behavior in bash.

Without fancynewline

dave @ [ manilla :: (Darwin) ] ~ $ echo hello
hello
dave @ [ manilla :: (Darwin) ] ~ $ echo -n hello
hellodave @ [ manilla :: (Darwin) ] ~ $

With fancynewline

dave @ [ manilla :: (Darwin) ] ~ $ echo hello
hello
dave @ [ manilla :: (Darwin) ] ~ $ echo -n hello
hello%
dave @ [ manilla :: (Darwin) ] ~ $

Credits

# http://stackoverflow.com/questions/2575037/how-to-get-the-cursor-position-in-bash
# print the current column of the cursor
curcol() {
local pos oldstty row=0 col=0
exec < /dev/tty
oldstty=$(stty -g)
stty raw -echo min 0
tput u7 > /dev/tty
IFS=';' read -r -d R -a pos
stty "$oldstty"
# change from one-based to zero based so they work with: tput cup $row $col
col=${pos[1]}
col=$((${col:-1} - 1))
echo "$col"
}
# conditonally output `%\n` based on the current column of the cursor
fancynewline() {
if (( $(curcol) != 0 )); then
tput bold
tput rev
echo '%'
tput sgr0
fi
}
PROMPT_COMMAND=fancynewline
@bahamas10
Copy link
Author

This has an issue, if you start typing in a command before the last command has finished, anything typed will be lost.

ie. run sleep 3, and as it's running type ls<enter>. normally, once the sleep has finished ls will be executed, but with this in place, the text ls<enter> will be lost.

@zendeavor
Copy link

this also doesn't seem to work under screen-256color terminfo

@ihodes
Copy link

ihodes commented Sep 18, 2013

In order to make work under screen-256color terminfo (which is what tmux uses), compile the following terminfo with tic https://gist.github.com/4770f748854f37c97fcb and use that with tmux instead (in ~/.tmux.conf set -g default-terminal "screen-256color-new").

@ihodes
Copy link

ihodes commented Sep 18, 2013

(It adds u7 (user string 7) to the terminfos, which xterm has defined, which is used with tput to get the cursor location).

@ihodes
Copy link

ihodes commented Sep 18, 2013

Though I suppose more easily the script could be modified to use echo -en "\033[6n" in lieu of tput u7.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment