Shebangs and script permissions
Two ways to run a script
When you run bash hello.sh, you choose the interpreter explicitly. When you execute ./hello.sh on Linux, the operating system can use the first line of the executable file to choose an interpreter. A shebang starts with #! and names an interpreter; it must be the first line, with no preceding blank line or byte-order mark.
#!/usr/bin/env bashprintf '%s\n' 'Hello from Bash'Expected output when executed:
Hello from Bash/usr/bin/env bash asks the env utility to locate Bash using PATH, the configured command search locations. This can accommodate Bash installed in different directories, but depends on a trusted PATH and the availability of /usr/bin/env. #!/bin/bash instead names an explicit interpreter location, which may not exist on every platform. In bash greet.sh, the selected Bash reads the first line as a comment; it does not switch interpreters because of it.
Allow direct execution of your own file
Save the previous example as a new greet.sh in the lab directory. Run these commands only on that practice file. chmod u+x adds owner execute permission; ./ identifies a path in the current directory. As in the previous lesson, && stops the chain on failure. Direct execution also depends on directory access, a usable interpreter and filesystem execution policy.
bash greet.sh && chmod u+x greet.sh && ./greet.shExpected output when executed:
Hello from BashHello from BashExecution is not sourcing
A command such as bash greet.sh starts a separate Bash process. The source command (also written as . in portable shell syntax) reads a trusted file in the current shell instead. A sourced script may change the current shell’s variables or directory, and an exit inside it may end that shell. Use ordinary execution for these beginner scripts; do not source unknown files.
Common mistakes
If direct execution reports permission denied, verify the file, interpreter and execution policy rather than applying chmod 777, changing permissions recursively or using sudo. On Windows-mounted filesystems or other restricted filesystems, direct execution may differ. The explicit bash greet.sh form is enough for these practice scripts when Bash can read the file.
Practice
Create a fresh welcome.sh with a shebang and one printed line. Run it via Bash, add owner execute permission, then run it directly where supported. Explain why the two commands use different interpreter-selection paths.
Next lesson: Comments, syntax errors and help