The two commands you have just learned,
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:
- You wrote the shell script months (or years) ago and cannot recall exactly how you did things
- Someone else wrote a shell script and you need to update it or use it as the basis for another project
- You want to improve the appearance of the shell script to make it easier to follow what’s going on in it
- When to use Comments: For both of these reasons, comments are added to scripts to explain what each command or section of commands does. Comments are not interpreted by the shell: they are ignored. So adding many comments does not affect the speed of your shell script. Shell script comments generally should not explain the meaning of the commands themselves. You will become very familiar with the commands. Rather, comments should explain why you use a certain command or what it accomplishes in the script overall. For example, a poor comment would be:
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.
You can set your PATH environment variable to tell the shell where to search for programs (and scripts) to be run. The main system commands are in /bin, /usr/bin, /sbin, and /usr/sbin, but you may have your own scripts in $HOME/bin, $HOME/scripts, /usr/local/bin, or elsewhere. Append these to the PATH so that they will be found by the shell even when you are not in that directory:
PATH=${PATH}:${HOME}/bin
Without the PATH, you will need to provide an explicit path (either absolute or relative) to the command.
For example:
$ myscript.sh
bash: myscript.sh: command not found
$ /home/steve/bin/myscript.sh
... or:
$ cd /home/steve/bin
$ ./myscript.sh
You can use sed command to comment lines between two line numbers. Example:
sed -i '10,30 s/^/#&/' mycode.sh
Above code will comment the code between line 10&30.
The next lesson describes how to set a shell script file’s permissions to allow it to be executed.