Skip to content

Instantly share code, notes, and snippets.

@doak
Forked from viking/i3-shell.sh
Last active November 25, 2019 17:26
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 doak/f9bb4bbe3cae8afaa8eb8cf3755de8be to your computer and use it in GitHub Desktop.
Save doak/f9bb4bbe3cae8afaa8eb8cf3755de8be to your computer and use it in GitHub Desktop.
Bash script for i3 to run a terminal in the same working directory as the current focused application
#!/usr/bin/env bash
# Based on 'i3' thread [1] and Github Gist [2]:
# [1] https://faq.i3wm.org/question/150/how-to-launch-a-terminal-from-here/?answer=152#post-id-152
# [2] https://gist.github.com/viking/5851049
find_cwd_of_forground_process() {
local pid="$1"
local cwd
for pid in `find_childs "$pid"`; do
pid="`find_forground_pid "$pid"`" ||
continue
[ "$pid" -ne -1 ] ||
continue
# Use this PID if there is a working directory specified.
[ -e "/proc/$pid/cwd" ] ||
continue
readlink "/proc/$pid/cwd"
return 0
done
return 1
}
find_childs() {
local pid="$1"
pstree -lpATn "$pid" |
grep -oP '\(\K[^)]+(?=\))'
}
find_forground_pid() {
local pid="$1"
ps -ho tpgid "$pid" |
sed 's/\s//g'
}
# Get window ID.
ID="$(xdpyinfo | grep focus | cut -f4 -d " ")"
# Get PID of process whose window this is.
PID="$(xprop -id "$ID" | grep -m 1 PID | cut -d " " -f 3)"
# Get CWD of first forground process within its childs.
CWD="$(find_cwd_of_forground_process "$PID")"
if [ -n "$CWD" ]; then
cd "$CWD"
fi &&
exec "$@"
@doak
Copy link
Author

doak commented Nov 25, 2019

It lasts quite long if firefox is active (with a lot of threads). Hence I ignore threads for now (option -T for pstree),

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