Home Shell Scripting All Sections
 
Shell Scripting: Beginners
A beginner's guide to shell scripting with simple examples of 'date' and 'grep'

Manpages
Man sh
Man tcsh
Man chmod
Man du
Man date
Man grep
Pipelines
Redirection
 


Hosted by...
Linode
 

Sponsored Links

 

Since shell scripting is nothing but a bunch of standard UNIX commands thrown together, we need a way of 'linking' two commands together. Say for example we wanted to print the date only if it is the 13th of the month and it is a Friday. We want to check this every day automatically. How can we tell /bin/date to only show us the date when this condition is met? There is a common UNIX program called grep that only outputs lines matching what we tell it to match. Wouldn't it be nice to be able to take the date (one line of output) a send it straight to grep? We can do just that!

/bin/date +"%a %b %e" | grep Fri | grep 13

The string following /bin/date in the above example formats the date so it will be displayed in the Sat Oct 13 format. Notice there is no time in this format because time could show up as 13 which could have our date show when it is not supposed to. The way we passed the date string to grep is called a pipe. A pipe character is a shift+\ key (usually just over the enter key on a standard pc keyboard).

Many useful applications can be created with the small amount of information given above, but we're limited to outputting to our screen. Many times, we will want to have the output of our script go straight into a file. File-output redirection can be accomplished by simply putting a > character followed by the name of the file to create/overwrite. For example:

/bin/ls -lR ~ > ~/file_tree.log      (Note: running this command could take a very long time depending on how big your home directory is and it could also take up quite a bit of disk space! Be careful!)

As mentioned before, the > redirection creates or overwrites a file. Make sure not to overwrite something important! To append to a file, use >> redirection. To take prompt input from a file, the <character is used. To send the output of a program to another, the '|' character (called a pipe) is used.

/bin/date +"%a %b %e" >> ~/times.log
/bin/cat ~/times.log | grep Fri | grep 13

The previous commands will 1) add the date to the end of the ~/times.log file and 2) print all of the lines added to ~times.log on Friday 13.

 
Manpages About Webmaster