Forgetting to Set Execute Permissions

Problem

You got your script all written and want to try it out, but when you go to run the script you get an error message:

$ ./my.script
bash: ./my.script: Permission denied
$

Solution

You have two choices. First, you could invoke bash and give it the name of the script as a parameter:

$ bash my.script

Or second (and better still), you could set the execute permission on the script so that you can run it directly:

$ chmod a+x my.script
$ ./my.script

Discussion

Either method will get the script running. You’ll probably want to set the execute permissions on the script if you intend to use it over and over. You only have to set the permissions once, thereafter allowing you to invoke it directly. With the permissions set it feels more like a command, since you don’t have to explicitly invoke bash (of course behind the scenes bash is still being invoked, but you don’t have to type it).

In setting the execute permissions, we used a+x to give execute permissions to all. There’s little reason to restrict execute permissions on the file unless it is in some directory where others might accidentally encounter your executable (e.g., if as a system admin you were putting something of your own in /usr/bin). Besides, if the file has read permissions for all then others can still execute the script if they use our first form of invocation, with the explicit reference to bash. Common permissions on shell scripts are 0700 for the suspicious/careful folk (giving read/write/execute ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.