1

I made a bash file "my_sh.sh". by default it has no x permission:

-rw-rw-r-- 1 amin amin 37 Mar 12 00:45 my_sh.sh

But I could run it without any problem or warning! Why?

amin@ubuntu:~/newDIR$ bash my_sh.sh
Amin
  • 91
  • 1
    What you are running here is bash and not my_sh.sh (it's an argument to bash), thus bash should be executable which it is, to check it out: ls -l $(which bash). – Ravexina Mar 12 '19 at 08:27

1 Answers1

3

There is a difference in ./my_sh.sh and bash my_sh.sh

./my_sh.sh tells the kernel that it's a script which then looks at the first line (the shebang #!) and uses said interpreter (?) to run the script, it needs have executable permissions for the kernel to do this. Edit: This will start another process as we are starting a new instance

bash my_sh.sh is asking bash to run the script and doesn't care so much of the first line. So (correct me if I am wrong) it just needs read permissions for bash to run it

Note that there are plenty of other scripts we can write just like .sh scripts, python for example:

python my_py.py is different from ./my_py.py (<= assuming you have the proper shebang)

As was stated in the comments, when writing script files, leaving out the shebang line, the script will use the current shell environment which if the script uses a different shell ie the script uses ksh but your shell environment is bash (thank you Sergiy Kolodyazhnyy for the example :) ) this can lead to errors.

j-money
  • 2,382
  • 1
    Another example would be that you could use python foo.py without the +x permission set, as long as /usr/bin/python has the permission. – Kristopher Ives Mar 12 '19 at 08:33
  • ooh great point :D I'll add it to the answer, thanks! – j-money Mar 12 '19 at 08:34
  • Note that if #! line is not found in the file, then the script is executed in current shell environment, which can lead to errors if the script is using ksh shell features for example, but your current shell is bash. This also means that script with #! runs as separate process (because new shell instance would have to be started), whereas script without #! is not. – Sergiy Kolodyazhnyy Mar 12 '19 at 10:04
  • @SergiyKolodyazhnyy "... then the script is executed in current shell environment" I didn't know this!! Thank you!! – j-money Mar 12 '19 at 10:06
  • @j-money You're very welcome. Feel free to incorporate the comment into your answer so others can see. Comments are meant mostly for improvements and are subject to deletion, so I guess such info is better integrated into answer itself :) – Sergiy Kolodyazhnyy Mar 12 '19 at 10:08