Nautilus: Open current folder in VS Code through a keyboard shortcut

What I want to do:
I’m trying to make it so that when I have a folder open in Nautilus, I can run a script or command that will open that same folder in Visual Studio Code through a keyboard shortcut.

What I’ve tried:
I used

nautilus_path=$(xdotool getactivewindow getwindowname | sed ‘s/^.* — //’)

to extract the folder name from the Nautilus window title and then run:

code “$nautilus_path”

But this only works if the folder is inside my home directory or if I’m already in its parent directory in the terminal. It fails for nested directories or paths outside $HOME.

Problem:
The variable I get from the window title is just the folder name, not the full absolute path, so VS Code can’t find it.
For example
Let’s say i want to open the dir /home/$USER/Documents/dir
but nautilus path would return just dir instead…

Question:
How can I reliably get the full path of the current Nautilus window’s folder so I can pass it to code?
I’m fine with using scripts, xdotool, or D-Bus (org.gnome.Nautilus) if needed.

In ~/.local/share/nautilus/scripts/my_first_script.sh, write a script that uses the variables demonstrated here for your own actions. Note that the variable is a space separated list, and URIs of local files will start with file:///. Also don’t forget to set it to executable.

#!/bin/bash
echo Selected File Paths: $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
echo Selected File URIs: $NAUTILUS_SCRIPT_SELECTED_URIS
echo Current location URI: $NAUTILUS_SCRIPT_CURRENT_URI

In ~/.config/nautilus/scripts-accels, add a shortcut and the script name associated with it:

<control>y my_first_script.sh

See Gtk.accelerator_parse and Gtk.ShortcutTrigger.parse_string for more info on how to format the shortcut.

1 Like

Thank you, it works, didn’t know that Nautilus sets special environment variables that I can use directly, also that scripts-accels thing for defining shortcuts!

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.