Skip to content

Instantly share code, notes, and snippets.

@wknapik
Last active December 28, 2022 13:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wknapik/1818bb19344786dee9b0f4d51c274dc2 to your computer and use it in GitHub Desktop.
Save wknapik/1818bb19344786dee9b0f4d51c274dc2 to your computer and use it in GitHub Desktop.
[tmux/zsh] Print matching lines of output (stdout and stderr) from the last command run in an interactive shell, without rerunning the command
# This function greps everything between the last two prompts in the current tmux pane.
# Arguments are passed to `grep -i', so any valid `grep' options can be supplied.
# Requirements: coreutils, grep, sed, tmux, zsh.
just() {
local -r max=10000 psone="$(print -P "$PS1"|sed "s,\x1B\[[0-9;]*[a-zA-Z],,g")"
local inside=0;
tmux capture-pane -pS-"$max" -E"$max"|tac|\
while IFS= read -r line; do
case "$inside,$line" in
1,"$psone"*) break;;
1,*) echo "$line";;
0,"$psone"*) inside=1;;
esac;
done|tac|grep -i "$@"
}
# Command output containing PS1 and/or changing prompts will mess with this
# (e.g. last exit code in PS1, etc.), see comments.
# Example usage:
#
# % ls -1 /bin
# arch
# ash
# base64
# [...]
# % just name
# dnsdomainname
# hostname
# uname
# % just ^h
# hostname
# %
@wknapik
Copy link
Author

wknapik commented Dec 12, 2019

Modification for prompts that may have the last exit code at the beginning

just() {
    local -r max=10000 psone="$(print -P "$PS1"|sed -e "s,\x1B\[[0-9;]*[a-zA-Z],,g" -e 's/^[0-9]\{1,3\} //g')"
    local inside=0;
    tmux capture-pane -pS-"$max" -E"$max"|tac|\
        while IFS= read -r line; do
            case "$inside,$line" in
                *,[0-9][0-9][0-9]" $psone"*|*,[0-9][0-9]" $psone"*|*,[0-9]" $psone"*|*,"$psone"*)
                    if ((inside == 1)); then break; else inside=1; fi;;
                1,*) echo "$line";;
            esac;
        done|tac|grep -i "$@"
}

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