4

Assuming i am in a bash shell now and i execute the following

[me@server]$ bash script.sh

q1) Is a new child bash process created to execute the script ?

If i do a

[me@server]$ ./script.sh

q2) Is a new child bash process created to execute the script ?

q3) What is the difference between the 2 methods then ?

1

2 Answers 2

1

From Dot slash explanation

The difference you do is,

with sh, you're running a program that will interpret the lines in your script just as it you would have typed them on the interactive prompt of the terminal,

with ./ you're making a shortcut assuming that the script is just right here in the current directory you're sitting in AND it will be executable (because for instance you issued chmod +x myscript.sh),

Additional info from this answer :

For your specific script either way will work, except that ./script.sh requires execution and readable bits, while bash script.sh only requires readable bit.

The reason of the permissions requirement difference lies in how the program that interprets your script is loaded:

./script.sh makes your shell run the file as if it was a regular executable. The shell forks itself and uses a system call (e.g. execve) to make the operating system execute the file in the forked process. The operating system will check the file's permissions (hence the execution bit needs to be set) and forward the request to the program loader, which looks at the file and determines how to execute it. In Linux compiled executables start with an ELF magic number, while scripts start with a #! (hashbang). A hashbang header means that the file is a script and needs to be interpreted by the program that is specified after the hashbang. This allows a script itself to tell the system how to interpret the script.

With your script, the program loader will execute /bin/bash and pass ./script.sh as the command-line argument.

bash script.sh makes your shell run bash and pass script.sh as the command-line argument So the operating system will load bash (not even looking at script.sh, because it's just a command-line argument). The created bash process will then interpret the script.sh because it's passed as the command-line argument. Because script.sh is only read by bash as a regular file, the execution bit is not required.

0
  1. a child bash process is create
  2. same as above (due to shebang)
  3. the two are equivalent, if you do not want to fork a child, or want to keep env value from script.sh, use

    . ./script.sh
    

beware however

  • if script.sh call exit, you will exit current shell.
  • if shell end with no error you are return to initial shell.
1
  • 1
    . script is the same as source script - see help source (at bash prompt) for more.
    – Hannu
    Jul 9, 2015 at 16:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .