| Lesson 7 |
Including comments in shell scripts |
| Objective |
Add clear comments and self-documenting names to make shell scripts easier to understand and maintain. |
Including Comments in Shell Scripts
The commands you have just learned (
echo and
read) are straightforward. But as scripts grow, the intent behind a sequence of commands can become unclear—especially when:
- You revisit a script months (or years) later and no longer remember why it was written a certain way
- Someone else wrote the script and you need to troubleshoot or extend it
- You want the script to be readable enough that it can be safely maintained
What Good Comments Explain
How to Add Comments in Shell Scripts
Self-Commenting Code
Environment Context That Affects Script Readability
Two environment settings commonly affect the “feel” of a terminal session and how scripts are executed: your prompt (PS1) and your PATH.
PS1 Prompt
PS1 controls the shell prompt displayed in your terminal. A common prompt format is:
\u@\h:\w$
Example:
steve@goldie:/var/log$
This shows the username, host, and current working directory. A readable prompt can reduce mistakes and make copy/pasted command examples easier to follow.
PATH Environment Variable
The
PATH variable tells the shell where to search for programs (and scripts). System commands often live in directories such as
/bin and
/usr/bin. Your own scripts might live in
$HOME/bin or
/usr/local/bin.
You can extend your PATH like this:
PATH="${PATH}:${HOME}/bin"
Without PATH pointing to your script directory, you must run scripts using an explicit path:
$ myscript.sh
bash: myscript.sh: command not found
$ /home/steve/bin/myscript.sh
# or:
$ cd /home/steve/bin
$ ./myscript.sh
Example: Comments + Script Flow
What This Example Demonstrates
- The shebang line selects the interpreter (
#!/bin/sh).
- Section headers group related steps (the block comment at the top).
- Inline comments explain “why this step exists,” not obvious syntax.
read -r safely captures user input without backslash escaping surprises.
- The
if test is spaced and quoted correctly to avoid syntax and word-splitting errors.
Modern Technique: Commenting Blocks Quickly
The next lesson describes how to set a shell script file’s permissions so it can be executed.
