About script execution permissions on Linux shell

Viewed 112

Here's the thing:

  • I've just created a script, let's say, "helloworld.sh".
  • The script doesn't yet have execution permissons: -rw-rw-r--
  • With that said, if I try to execute that script with: "./helloword.sh", I'll get an error message, as expected.
  • But, if I try to execute that same script as: ". helloword", it will execute with no problems.

So, my question is, How ? Why does that happen?

1 Answers

This happens because on Linux the "." (dot) alone is a built-in command that execute the script within your current session with your current shell. This is the same as calling the script with source command (the BSD default method). It's almost the same than execute with bash helloworld.sh.

When you call the script with ./helloworld.sh or /root/helloworld.sh the shell will try to figure out how to execute it, if the file is a binary, it will simply run, if it is a script, the shell will read the first line looking for the interpreter. To do this, you'll need execution permission.

To simplify:

  • One is a command;
  • The other one is a path.

You can even run:

. --help

About . against bash:

This is why we use . or source to load variables from a file in our session, for example, when we change ~/.bashrc and reload it without login again.

You can see this happens when you execute:

. /etc/os-release

All variables defined inside this file will be loaded and available in your current shell session.

The same will not happen if you execute:

bash /etc/os-release

Because you opened a "new session" inside that bash that you called, the new bash executes and close, cleaning the session.

The same process happen if you give execute permission +x to the script, because when you call the script with ./ or something like that, a new session will be created too.

Related