Linux

  1. Home
  2. Computing & Technology
  3. Linux

Bash Guide For Beginners

From Authors, for About.com

2.2.2. Adding comments

You should be aware of the fact that you might not be the only person reading your code. A lot of users and system administrators run scripts that were written by other people. If they want to see how you did it, comments are useful to enlighten the reader.

Comments also make your own life easier. Say that you had to read a lot of man pages in order to achieve a particular result with some command that you used in your script. You won't remember how it worked if you need to change your script after a few weeks or months, unless you have commented what you did, how you did it and/or why you did it.

Take the script1.sh example and copy it to commented-script1.sh , which we edit so that the comments reflect what the script does. Everything the shell encounters after a hash mark on a line is ignored and only visible upon opening the shell script file:


   

#!/bin/bash
# This script clears the terminal, displays a greeting and gives information
# about currently connected users. The two example variables are set and displayed.

clear # clear terminal window

echo "The script starts now."

echo "Hi, $USER!" # dollar sign is used to get content of variable
echo

echo "I will now fetch you a list of connected users:"
echo
w # show who is logged on and
echo # what they are doing

echo "I'm setting two variables now."
COLOUR="black" # set a local shell variable
VALUE="9" # set a local shell variable
echo "This is a string: $COLOUR" # display content of variable
echo "And this is a number: $VALUE" # display content of variable
echo

echo "I'm giving you back your prompt now."
echo

In a decent script, the first lines are usually comment about what to expect. Then each big chunk of commands will be commented as needed for clarity's sake. Linux init scripts, as an example, in your system's init.d directory, are usually well commented since they have to be readable and editable by everyone running Linux.


   Prev    Home    Next
   Creating and running a script    Up    Debugging Bash scripts

* License

* Bash Guide For Beginners Index

Explore Linux

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Linux

  1. Home
  2. Computing & Technology
  3. Linux
  4. Linux Documentation
  5. Bash Guide for Beginners
  6. Bash Guide For Beginners - 2.2.2. Adding comments

©2009 About.com, a part of The New York Times Company.

All rights reserved.