Repository navigation
Expand file tree
/
Copy pathcopy-last-cmd
More file actions
executable file
·49 lines (43 loc) · 1.85 KB
/
Copy pathcopy-last-cmd
File metadata and controls
executable file
·49 lines (43 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/env bash
# copy-last-cmd — copy the last command's typed cmd + output to clipboard.
# Walks the pane scrollback for lines matching the prompt regex, extracts
# from just after the last-prompt terminating dollar-sign (i.e. the typed
# command) through the line before the current prompt, and hands it to
# pbcopy (or tmux paste buffer if pbcopy isn't around).
set -uo pipefail # no -e: a failed capture (e.g. TUI/altscreen pane with
# no history) is handled by the empty-text guard below,
# not by an abrupt bash exit.
# NOTE: keep this awk script assigned to a variable rather than inlined
# inside `awk '...'` in a `$(...)` — an apostrophe in a comment (say,
# `pane's`) will close bash's single quote and turn the rest of the awk
# block into a shell-syntax error. Assigning to a heredoc-fed var sidesteps
# that entirely.
awk_script=$(cat <<'AWK'
{ buf[NR] = $0 }
/ryan@mac.*\$/ { prev = cur; cur = NR }
END {
if (prev == 0) exit
line = buf[prev]
# Strip up to (but not including) the prompt terminating $, so the
# extracted line reads like a GHMD `console` fence: `$ typed-cmd`.
# `[^$]*` stops at the first $ after `ryan@mac`, so a typed command
# like `echo $HOME` stays intact.
sub(/.*ryan@mac[^$]*/, "", line)
print line
for (i = prev + 1; i < cur; i++) print buf[i]
}
AWK
)
text=$(tmux capture-pane -p -S -3000 2>/dev/null | awk "$awk_script")
if [ -z "$text" ]; then
tmux display-message 'copy-last-cmd: no prompt lines matched in this pane'
exit 0
fi
lines=$(printf '%s\n' "$text" | wc -l | tr -d ' ')
if command -v pbcopy >/dev/null 2>&1; then
printf '%s\n' "$text" | pbcopy
tmux display-message "Copied last cmd ($lines lines) to clipboard"
else
printf '%s\n' "$text" | tmux load-buffer -
tmux display-message "Copied last cmd ($lines lines) to tmux buffer"
fi