24.07.2018 Views

Bash-Beginners-Guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Bash</strong> <strong>Guide</strong> for <strong>Beginners</strong><br />

Once you found the buggy part of your script, you can add echo statements before each command of which<br />

you are unsure, so that you will see exactly where and why things don't work. In the example<br />

commented-script1.sh script, it could be done like this, still assuming that the displaying of users gives<br />

us problems:<br />

echo "debug message: now attempting to start w command"; w<br />

In more advanced scripts, the echo can be inserted to display the content of variables at different stages in the<br />

script, so that flaws can be detected:<br />

echo "Variable VARNAME is now set to $VARNAME."<br />

2.4. Summary<br />

A shell script is a reusable series of commands put in an executable text file. Any text editor can be used to<br />

write scripts.<br />

Scripts start with #! followed by the path to the shell executing the commands from the script. Comments are<br />

added to a script for your own future reference, and also to make it understandable for other users. It is better<br />

to have too many explanations than not enough.<br />

Debugging a script can be done using shell options. Shell options can be used for partial debugging or for<br />

analyzing the entire script. Inserting echo commands at strategic locations is also a common troubleshooting<br />

technique.<br />

2.5. Exercises<br />

This exercise will help you to create your first script.<br />

1. Write a script using your favorite editor. The script should display the path to your homedirectory and<br />

the terminal type that you are using. Additionally it shows all the services started up in runlevel 3 on<br />

your system. (hint: use HOME, TERM and ls /etc/rc3.d/S*)<br />

2. Add comments in your script.<br />

3. Add information for the users of your script.<br />

4. Change permissions on your script so that you can run it.<br />

5. Run the script in normal mode and in debug mode. It should run without errors.<br />

6. Make errors in your script: see what happens if you misspell commands, if you leave out the first line<br />

or put something unintelligible there, or if you misspell shell variable names or write them in lower<br />

case characters after they have been declared in capitals. Check what the debug comments say about<br />

this.<br />

Chapter 2. Writing and debugging scripts 28

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!