-
Notifications
You must be signed in to change notification settings - Fork 0
/
lastcwd
executable file
·56 lines (49 loc) · 1.71 KB
/
lastcwd
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
50
51
52
53
54
55
56
#!/usr/bin/env bash
# shellcheck disable=SC2009
# Fail on errors.
set -eEo pipefail
shopt -s inherit_errexit >/dev/null 2>&1 || true
# Print foreground descendant pid for given pid, or 0.
foreground_pid() {
local -ra pids=("$@")
if [[ -n "${pids[*]}" ]]; then
local -a tmp=() cpids=()
local pid wid
for pid in "${pids[@]}"; do
if ps -o stat:1= "$pid"|grep -qFm1 +; then
wid="$(ps e -o args= "$pid"|grep -o "WINDOWID=[0-9][0-9]*"|cut -d= -f2 || true)"
if [[ -n "$wid" && "$wid" == "$((window_id))" ]]; then
echo "$pid"
return
fi
else
read -ra tmp <<<"$(ps -o pid:1= --ppid "$pid"|tr '\n' '\t')"
cpids+=("${tmp[@]}")
fi
done
foreground_pid "${cpids[@]}"
else
echo 0
fi
}
# Print cwd for pid.
pid_cwd() { pwdx "$1"|cut -d' ' -f2-; }
# Establish active window and its pid.
window_id="$(xprop -root 32x '\t$0' _NET_ACTIVE_WINDOW|cut -f2)"
window_pid="$(xprop _NET_WM_PID -id "$window_id"|cut -d' ' -f3)"
# Establish foreground pid. Don't bother if none of window_pid's children have a tty.
if ps -o tty= --ppid "$window_pid"|grep -qv '^?$'; then
fgpid="$(foreground_pid "$window_pid")"
else
fgpid=0
fi
# Print cwd for foreground process with special handling for tmux.
if [[ "$fgpid" -eq 0 ]]; then
pid_cwd "$window_pid"
elif ps -o comm:1= "$fgpid"|grep -q '^tmux'; then
client_name="$(tmux list-clients -F '#{client_name} #{client_pid}'|grep " $fgpid\$"|cut -d' ' -f1)"
fgpid2="$(foreground_pid "$(tmux display-message -t "$client_name" -p '#{pane_pid}')")"
pid_cwd "$fgpid2"
else
pid_cwd "$fgpid"
fi