custom context menus with nautilus scripts

October 15th, 2007
Nautilus Scripts allow GNOME users to easily add custom context menu items that invoke specific commands or scripts.

To add a new menu item you have to create a shell script inside your ~/.gnome2/nautilus-scripts directory and make it executable. To invoke the script from the menu right click on Nautilus and go to Scripts. Your shell script should be there. When executed, the script inherits the current working directory from Nautilus.

For example, let's say that we want to add a menu item that will open a new terminal in the current folder.

We go to the folder where all Nautilus Scripts reside:

cd ~/.gnome2/nautilus-scripts

We create our shell script, let's call it open-terminal.sh:

gedit open-terminal.sh

We add the following lines in the file:

#!/bin/sh
gnome-terminal


Save the file and make it executable:

chmod +x open-terminal.sh

Now if you right click on nautilus and go to Scripts you should be able to see your new script:

a screenshot showing nautilus scripts menu


If you do not see it, make sure that you did the whole procedure correctly. If it still does not show up try to press F5 (reload) or restart Nautilus.

Usually you will want to add a custom script that will perform a specific action on the selected file or files. For local directories, Nautilus will call your shell script passing the selected file or files as command line arguments to the script.

To demonstrate this we will now create another script that will open the selected file for edit in the vi editor (which will run inside gnome-terminal). Go to ~/.gnome2/nautilus-scripts again and create another shell script by the name open-with-vi.sh:

cd ~/.gnome2/nautilus-scripts
gedit open-with-vi.sh


Add the following commands:

#!/bin/sh
gnome-terminal -x vi $1


Save the file and make it executable:

chmod +x open-with-vi.sh

Then go to Nautilus and select a text file. Right click on it, go to Scripts and choose open-with-vi.sh:

screenshot of nautilus scripts menu


You should see a gnome terminal running vi with your file open for editing:

screenshot of GNOME terminal running vi


When the script is executed $1 is replaced by the selected file's name. If you want to handle multiple files you will have to traverse all the command line arguments passed to the script, $1, $2, $3, and so on.

Finally, it would be worth to mention that you can organize your Nautilus Scripts in subdirectories inside ~/.gnome2/nautilus-scripts. The subdirectories will appear in the context menu as sub-menu items.

One Response to “custom context menus with nautilus scripts”

  1. Tortoise SVN in Linux? Ubuntu alternatives here.. - KrishnaShasankar.com Says:
    [...] morning i can across this blog about how to implement scripts in nautilus that allows users to replicate TortoiseSVN like [...]

Leave a Reply