Lesson 7 | Including comments in shell scripts |
Objective | Explain the importance of comments in a shell script. |
echo
and read
, are straightforward. But as scripts become longer and more complex, the meaning of commands is sometimes difficult to determine. This is especially true when:
Test the value of the variable. If someone reads your script, they might think:
“Yes, I can see that, but why are you testing it?”A better comment would be:
Test whether flight number is within a valid range.
#
.
When the shell finds a # character, everything until the end of the line is ignored. In a large shell script, a block of comment lines are often used to introduce a section of the script, something like this:
#=================================== # Test flight numbers stored in travel records # to determine validity. Base on the airline # place records in appropriate database directory # # Created 12 Nov 2009; Modified 20 Jan 2010; # N. Wells for FarAway.com #===================================
#!/bin/sh
.
This was described in an earlier lesson in this module.
#!/bin/sh #================================= # This sample script contains only # a few commands # ================================ # Request username and record for later use echo Please enter your name: read MYNAME # Confirm that the name is correct before proceeding echo Is $MYNAME the correct name? read ANSWER if[ANSWER ="Y"] thenThe first line of the script names the command interpreter.
#!/bin/sh #================================= # This sample script contains only # a few commands # ================================ # Request username and record for later use echo Please enter your name: read MYNAMEThe next read command is executed, and the script proceeds with other commands, skipping all comment lines.
sed -i '10,30 s/^/#&/' mycode.sh