Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Script to get the CWD of the current active window, with support for shells running tmux. This can be used to launch new terminals in the same cwd as the current one.
# i3 thread:
# Inspired by but with support for tmux
# 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 last child process (shell, vim, etc)
if [ -n "$PID" ]; then
TREE=$(pstree -lpA $PID | tail -n 1)
PROCESS=$(echo $TREE | awk -F'---' '{print $NF}')
PID=$(echo $TREE | awk -F'---' '{print $NF}' | sed -re 's/[^0-9]//g')
# If we're in a tmux session then we need to do some gymnastics to get the
# cwd since the tmux session is not a direct child of the terminal
if [[ $PROCESS == tmux* ]];
# To get the pid of the actual process we:
# - find the pts of the tmux process found above
PTS=$(ps -ef | grep $PID | grep -v grep | awk '{print $6}');
# - find the tmux session that's attached to the pts
TMUX_SESSION=$(tmux lsc -t /dev/${PTS} -F "#{client_session}")
# - find the pane_pid of the session
PID=$(tmux list-panes -st $TMUX_SESSION -F '#{pane_pid}')
# If we find the working directory, run the command in that directory
if [ -e "/proc/$PID/cwd" ]; then
CWD=$(readlink /proc/$PID/cwd)
echo $CWD
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.