010-150 · Question #10
How is it possible to determine if an executable file is a shell script which is read by Bash?
The correct answer is C. The first line starts with #!/bin/bash. A shell script executed by Bash is identified by the shebang line at the top of the file, which tells the kernel which interpreter to use.
Question
How is it possible to determine if an executable file is a shell script which is read by Bash?
Options
- AThe r bit is set.
- BThe file must end with .sh.
- CThe first line starts with #!/bin/bash.
- D/bin/bash has to be run in debug mode.
- EScripts are never executable files.
How the community answered
(36 responses)- B6% (2)
- C81% (29)
- D3% (1)
- E11% (4)
Why each option
A shell script executed by Bash is identified by the shebang line at the top of the file, which tells the kernel which interpreter to use.
The read bit (`r`) controls whether a file can be read, not which interpreter processes it - the execute bit (`x`) is what allows a file to run.
The `.sh` extension is a convention for human readability only; the kernel does not use file extensions to determine the interpreter for a script.
The shebang line `#!/bin/bash` on the first line of a file instructs the kernel to use `/bin/bash` as the interpreter when the file is executed. This is the standard POSIX mechanism for specifying a script interpreter, and it is how the system determines the file should be processed by Bash regardless of the file extension.
Running `/bin/bash` in debug mode (`-x`) is used for tracing script execution, not for identifying whether a file is a Bash script.
Shell scripts can be executable files; setting the execute permission on a script file and including a shebang line is the standard way to make them directly runnable.
Concept tested: Bash shebang line interpreter directive
Source: https://www.gnu.org/software/bash/manual/bash.html#Invoking-Bash
Topics
Community Discussion
5The answer is C. When the kernel executes a file, it reads the first two bytes for a magic number, and the shebang line #!/bin/bash tells it to hand the file off to Bash as the interpreter, which is what actually identifies it as a Bash script regardless of the filename or permissions beyond execute.
The shebang line tells the kernel which interpreter to hand the script off to, so #!/bin/bash is what marks it as a Bash script regardless of the filename or extension. Quick question though, do you know what happens when you run a script that has a shebang pointing to a different interpreter, like #!/usr/bin/env python3, but you also chmod +x it and call it from the terminal?
Thought .sh extension mattered until I ran file on a script with no extension and saw the shebang do all the work.
The .sh extension is the clearest, most consistent way to identify a Bash script.
Samuel, the extension is actually optional on Linux and means nothing to the kernel, so the reliable identifier is the shebang line at the top of the file, which is why C is correct.