Anatomy of a Script: Shebang and Comments
Open any script from a real project and the first line looks like line noise: #!/usr/bin/env bash. Below it come notes starting with #, and then ordinary commands. Once you can name these three kinds of line, every script becomes readable.
The rule
Shebang first, commands in order, and
#starts a comment.
Here is backup.sh, now written as a proper script:
#!/usr/bin/env bash
# backup.sh: pack the notes folder into ~/backups
mkdir -p ~/backups # make sure the target exists
tar -czf ~/backups/notes.tar.gz ~/notes # pack and compress
echo "Backup done"The shebang. #! must be the very first two characters of the file. When you run the file directly, the system reads this line to learn which interpreter to start. #!/bin/bash points at one fixed location; #!/usr/bin/env bash asks env to find bash on your PATH, which works even where Bash lives somewhere else (as on many macOS setups with a newer Bash installed).
Comments. A # at the start of a word begins a comment that runs to the end of the line. Bash ignores it. Use a header comment to say what the script does, and short end-of-line comments to explain why a line exists. But a # inside quotes, or in the middle of a word, is ordinary text:
echo "Total # of files" # prints: Total # of files
echo price#10 # prints: price#10Commands. Everything else runs top to bottom. Blank lines are ignored. A line ending in a backslash \ continues on the next line, which keeps long commands readable. Two short commands can share a line when separated by ;.
The shortcut
Read any script in three layers: line 1 answers who runs me; # lines answer why; everything else answers what happens, in order.
Line 1: who runs me
#!/usr/bin/env bashmeans "start bash, found on the PATH, and give it this file".
The classic mistake is putting a comment or blank line above the shebang. Then #! is no longer the first two characters, the system ignores it, and the file may be run by the wrong shell.
Drills
Answer fast — trust the rule.
Where must the shebang line go?
What does echo "Total # of files" print?
What does echo price#10 print?
Why do many scripts use #!/usr/bin/env bash instead of #!/bin/bash?
What does a backslash at the very end of a line do in a script?
Remember
- Shebang first, commands in order, and
#starts a comment. - Read in three layers: who runs me, why, what happens.
- Trap: anything above the shebang disables it; a
#in quotes or mid-word is not a comment.
