When you double-click on a shell script (.sh file), what do you expect? The normal expectation would be that it is executed. But this might not be the case in Ubuntu, or I should better say in the case of Files (Nautilus).
You may go crazy yelling, “Run, File, Run”, but the file won’t run instead, it gets opened in Gedit.
The shell script has execute permission but still, if I double-click on it, it is opened in a text editor. I don’t want it and if you are facing the same issue, I assume that even you don’t want it.
I know that you would have been advised to run it in the terminal and I know that it would work but that’s not an excuse for the GUI way to not work. Is it?
In this quick tutorial, we shall see how to make a shell script run within the nautilus files manager.
Make sure that the shell script is executable
Before trying to execute a shell script, you should ensure that the script has execution permission. It can be given through terminal commands and GUI. Since it is an article focussing on GUI, let’s check how to do this graphically.
On the nautilus file manager, right-click on the script file that you want to execute. From here, go to properties.
Inside the properties dialog box, go to the permissions tab and select the checkbox adjacent to Allow executing file as a program.
Now you can close the dialog box and the script should have execution permission.
Fix shell script opens in a text editor in Ubuntu 22.04 and higher
The reason why shell scripts are opening in the text editor is the default behavior set in Files (file manager in Ubuntu). In earlier versions, it would ask you if you want to run the file or open it for editing.
In recent versions of Nautilus, there are no more tweaks with the preference is available regarding this issue. Instead, if you have a script or any file having executable permission, the right-click context menu shows run as a program option.
You need to press the button to execute the script.
Also, it should be noted that the option to run a file appears only if the file has executable permission.
Fix shell script opens in a text editor [Older Ubuntu Versions]
On older Ubuntu versions (Ubuntu 20.04 LTS), you can set the default action on script files to run as a program from within preferences.
To do this, go into file manager, and from the top menu and click on Preference:
Next, in Files preferences, go to the Behavior tab, and you’ll see the option of “Executables Text Files“.
By default, it would have been set to “View executable text files when they are opened”. I would advise you to change it to “Ask each time” so that you’ll have the choice of whether to execute the shell scripts or edit but of course, you can set it by default for execution. It’s your choice here, really.
I hope this quick tip helped you to fix this little ‘issue’. Questions and suggestions are always welcomed.