A Simple Shell Script

team bbl


A shell script is a text file containing a series of commands that execute in sequence when the script is run. Shell scripts allow you to run several commands at once. Create the following simple shell script in a text editor (using text editors is discussed in Chapter 18) and save it with the name dir2file:

 #!/bin/bash # Script Name: dir2file - A simple shell script that saves a directory listing in a file ls -l > dirlist echo Directory is saved 

The first two lines are not commands, so they don't run. The lines begin with a pound sign (#), also called a hash mark, which means they don't execute. The first line tells Linux what program to use to run this script. In this case, the line (often called the shebang) calls the Bash shell. The first line of a Perl script would call Perl, rather than the shell. In this case, you could run the program without the shebang line, but the script is clearer with the line.

The second line is a comment. That is, a note to yourself. The shell ignores comments.

The last two lines are the commands that the shell script executes. The lines are exactly the same commands that you would enter at the command line. Chapter 7 explains how to use the command-line interface. Appendix B is a reference of commands. In this script, the ls command and the echo command are used. The ls command saves a long listing of the directory in a file named dirlist. When the ls command finishes, the echo command displays "Directory is saved" on the screen.

The script must have execute permissions in order to run. (Permissions are discussed in Chapter 9.) The following commands check and change the file permission, giving execute permission to the file owner:

 ls -l dir2file -rw-r--r-- 1 janet     janet     79  2005-01-09 15:57 dir2file chmod u+x dir2file ls -l dir2file -rwxr--r-- 1 janet     janet     79  2005-01-09 15:59 dir2file 

Now you can run the program as follows and see the output.

 ./dir2file Directory is saved 

If you list your directory now, you see file dirlist in your directory. If you display the file dirlist to the screen (cat dirlist), you see that it contains the output of ls -l.

    team bbl



    Spring Into Linux
    Spring Into Linux
    ISBN: 0131853546
    EAN: 2147483647
    Year: 2005
    Pages: 362
    Authors: Janet Valade

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net