Last active
February 19, 2022 08:07
-
-
Save TiddoLangerak/c61e1e48df91192f9554 to your computer and use it in GitHub Desktop.
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# i3 thread: https://faq.i3wm.org/question/150/how-to-launch-a-terminal-from-here/?answer=152#post-id-152 | |
# Inspired by https://gist.github.com/viking/5851049 but with support for tmux | |
CWD='' | |
# 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* ]]; | |
then | |
# 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}') | |
fi | |
# If we find the working directory, run the command in that directory | |
if [ -e "/proc/$PID/cwd" ]; then | |
CWD=$(readlink /proc/$PID/cwd) | |
fi | |
fi | |
echo $CWD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment