Mohammed Noureldin
Mohammed Noureldin

Reputation: 16906

Why do we need execution permission although we can run any script without it using "bash script file"?

I am wondering when and why do we need execution permission in linux although we can run any script without execute permission when we execute that script using the syntax bellow?

bash SomeScriptFile

Upvotes: 2

Views: 1878

Answers (2)

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

Executing the script by invoking it directly and running the script through bash are two very different things.

When you run bash ~/bin/SomeScriptFile you are really just executing bash -- a command interpreter. bash in turns load the scripts and runs it.

When you run ~/bin/SomeSCriptFile directly, the system is able to tell this file is a script file and finds the interpreter to run it. There is a big of magic invoking the #! on the first line to look for the right interpreter.

The reason we run scripts directly is that the user (and system) couldn't know or care of the command we are running is a script or a compiled executable.

For instance, if I write a nifty shell script called fixAllIlls and later I decide to re-write it in C, as long a I keep the same interface, the users don't have to do anything different.

To them, it is just a program to run.

edit

The operating system checks permissions first for several reasons:

  • Checking permissions is faster
  • In the days of old, you could have SUID scripts, so one needed to check the permission bits.
  • As a result, it was possible to run scripts that you could not actually read the contents of. (That is still true of binaries.)

Upvotes: 3

Jonathan Leffler
Jonathan Leffler

Reputation: 754480

Not all programs are scripts — bash for example isn't. So you need execute permission for executable programs.

Also, when you say bash SomeScriptFile, the script has to be in the current directory. If you have the script executable and in a directory on your PATH (e.g. $HOME/bin), then you can run the script without the unnecessary circumlocution of bash $HOME/bin/SomeScriptFile (or bash ~/bin/SomeScriptFile); you can simply run SomeScriptFile. This economy is worth having.

Execute permission on a directory is somewhat different, of course, but also important. It permits the 'class of user' (owner, group, others) to access files in the directory, subject to per-file permissions also allowing that.

Upvotes: 2

Related Questions