Network Administration: Linux Shell Scripts

A shell script is simply a text file that contains one or more commands. Shell scripts are similar to MS-DOS/Windows batch files, but shell scripts can be much more complex. The simplest shell scripts are just lists of commands, but advanced shell scripts can include complicated scripting statements that border on a full-featured programming language.

You can create shell scripts by using any text editor. The easiest text editor to use is gedit, which you can access from the GNOME desktop by choosing Main Menu→Accessories→Text Editor. If you want your friends to think you’re a Linux guru, however, take a few moments to learn how to use vi, a powerful text mode editor.

To create or edit a file in vi, type the command vi followed by a filename. Then, type away. To use a vi command, press the Escape key and then type one of the commands listed below.

Common vi Commands
Command Explanation
i Enters insert mode so that you can enter text at the cursor
location. Move the cursor to the point where you want to enter the
text first. When you’re finished inserting text, press Esc to
return to command mode.
:w Saves the file (w stands for write).
:q Quit.
:wq Write and then quit.
:q! Quit without saving.
/string Search forward for string.
?string Search backward for string.
n Repeat the last search.
u Undo the previous command.

After you’ve created a shell script, you have to grant yourself execute permission to run the script. For example, to grant yourself permission to run a script named myscript, use this command:

$ chmod 755 myscript

To run a shell script, you use the sh command and provide the name of the script file. For example:

$ sh myscript