Skip to content

Instantly share code, notes, and snippets.

@bxt
Last active April 9, 2017 19:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bxt/3804080 to your computer and use it in GitHub Desktop.
Save bxt/3804080 to your computer and use it in GitHub Desktop.
Change shell directory to one of the open directories in other shells
#!/bin/sh
# Retrieve a list of working directories by processes named like this one
# The ${0#-} strips the minus if we're on a login shell, i.e. $0 = '-bash'.
THELIST=$(lsof -F n -a -c ${0#-} -u $USER -d cwd \
| awk '/^n/ {print substr($0,2)}' | sort -u)
# Print the list with line numbers
echo "$THELIST" | nl
# Ask user to enter a line number to select directory
read NR
# On invalid or empty inputs go to last in list
if [[ ! "$NR" =~ ^[0-9]+$ ]]; then NR=$(echo "$THELIST" | wc -l); fi
# Save selected dir
THEDIR=$(echo "$THELIST" | awk 'NR=='$NR'{print;exit}')
# Change cwd to this dir
# This only works if you start this script with the dot command
# to run in the bash's environment and in a sub-shell.
# It is therefor recommended to set an alias like so: alias cd2='. cd2'
cd "$THEDIR"

cd2

cd2 is a tiny handy tool for working with multiple console windows at a time. When called, it displays a list of all working directories of your running terminals and lets you choose one by simply entering a number. If you enter nothing it takes you to the last entry listed which makes a good default behavior. This way, when you open a new terminal window and type cd2 and press enter twice you can continue in the same wd as your other bash.

Installing

To install for your user simply run:

curl https://gist.githubusercontent.com/bxt/3804080/raw/install | bash

or manually perform the steps of the script.

Running

Open a terminal and cd to some other directory. Then open another terminal and type cd2. You will see an output like this:

03:59  bxt@cindy:~> cd2
     1	/home/bxt
     2	/home/bxt/bin
     3	/home/bxt/some-other-dir

Press enter to go tho the last directory in the list, type any number and press enter to go to that directory.

Dependencies

Just basic tools like awk and lsof. Currently only tested with bash, feel free to comment if or not this works for you in other shells.

#!/bin/sh
curl https://gist.githubusercontent.com/bxt/3804080/raw/cd2 > ~/bin/cd2
chmod +x ~/bin/cd2
echo -ne "\n"\
"# Always run cd2 in current environment\n"\
"# Installed at `date`\n"\
"alias cd2='. cd2'\n\n" >> ~/.bashrc
echo cd2 installed successfully.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment