Use custom command to open files

gedit application is set as default application for text files. Supposing I have a script with execution rights in /usr/bin, how can I set that script to be run when I open a text file using Nautilus or xdg-open?

/usr/bin/foo:

echo "Works!"
gedit $*

If I do foo my_text_file, then Works! message will appear and gedit will run. How can I set this foo script to be run as default application?


The clean way would be to create a .desktop file for your script and then make it the default text editor.

  1. Create a file called /usr/share/applications/foo.desktop with the following contents:

    [Desktop Entry]
    Name=foo
    Exec=/usr/bin/foo.sh %U
    Terminal=false
    Type=Application
    MimeType=text/plain;
    
  2. Make it the default program for the text/plain mimetype:

    xdg-mime default foo.desktop "text/plain" 
    

As a dirty hack you could also simply call your script gedit:

sudo mv /usr/bin/gedit /usr/bin/gedit.orig
sudo mv /path/to/yourscript.sh /usr/bin/gedit

Then make your script call the original:

echo "Works!"
/usr/bin/gedit.original "$@"