I do not understand why do we use #!/bin/bash when writing scripts to use in BASH terminal?

codecademy.com/paths/web-development/tracks/learn-the-command-line/modules/bash-scripting/lessons/learn-bash-scripting/exercises/introduction

  1. Actually I understand that we need to use it to help the computer define that this is BASH scripts, but why does it work even without this string? I tried to run script file on my computer, and I did not type this string to define bash script, and it worked.

  2. We learned that we have to add a permission to the files to allow them to be run. But I did not have an error even if I had not write this string chmod +x script.sh.

So I do not understand why do we need to write these strings, if everything will work without them?

@ionatan might end up correcting me on this, as I am but a Linux noob compared to them, but…

As I understand it, the #! line at the start of your shell script is to identify the correct interpreter for the script.

Your scripts are running correctly without it in the LE because it’s defaulting to executing them in bash, but this may not always be the case.

1 Like

If you asked the kernel with a system call to execute that file, you’d get a response saying it’s not a valid executable file, however, you’re not asking linux directly, you’re asking bash, so it would seem that bash tries to run it as a shell script as a fallback.

You could make that system call from python:

$ python -c 'import os; os.execv("script.sh", ["script.sh"])'

If you ran it from something other than bash (like above), there might not be such a fallback.
Also you might get sh rather than bash, not sure.

1 Like